[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] OT Generic C question

From: Dave Hansen
Subject: Re: [avr-gcc-list] OT Generic C question
Date: Tue, 20 Sep 2005 10:04:13 -0400

From: "David Brown" <address@hidden>

----- Original Message -----
From: "Trampas" <address@hidden>
> I was helping a friend debug some code, he is new to C,  using the Keil
> version of GCC for ARM. Anyway I found the following:
> int i;
> i=0;
> i=i++;
> //i was still zero that
I'd agree with you that i should be 1 after "i = i++", despite the sillyness

Actually, I think the naive interpretation would be that i should be zero after the above is executed:

The statement implies three operations:

  1) read the variable on the RHS (i) and save the value
  2) increment the variable on the RHS (i).
  3) store the value preserved in step 1 (0) in the variable on the LHS (i)

The "logical" order of the operations is given above. In reality, the operations can occur in just about any order. The only guarantees the C standard makes about the order of execution involves a concept called "sequence points." Sequence point occur in several places, but the most common is at the end of each full expression (as a first estimation, you can think of it as being at each semicolon).

The standard says that the value of a variable should only be modified once between sequence points. The expression "i = i++;" attempts to modify i twice: once with the ++ operator and once with the = operator. Modifying a variable twice between sequence points is undefined behavior -- there is no "correct" answer. After the expression is executed, i could be 0, 1, 42, or the system might format your hard drive. All of the above and many other results are "legal" as far as the standard is concerned.

As other have pointed out, the correct way to get the desired effect is one of

  i += 1;
  i = i + 1;

Each of which should result in identical code.

Google on C sequence points for more information than you probably want.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]