Re: [LIP] Doubt in ++ operator
Binand Sethumadhavan <[email protected]>
| Newsgroups | gmane.user-groups.linux.india.programmers |
|---|---|
| Message-ID | <[email protected]> |
Vardhman Jain posted in linux-india-programmers:
> Hi,
> I have a doubt whether the following code should really be compiler
> dependent.
> int i=7;
> int j=i++ * i++;
> printf("%d",j);
>
> I think the answer should always be 49, as the ++ operator comes to
> action after the completion of the statement with the ';', But is
> there some reason the i++ should increment i before the next i++ is
> read means should the second i++ be read as 8 or 7?? Is this behaviour
> undefined in c ??
This behavoiur is undefined in C.
C has a concept called sequence points. In your code snippet, every
semicolon is a sequence point. The C standard says that an object can
be modified only once between two sequence points. Here, between the
two sequence points (end of line 1 and end of line 2), the object 'i'
is being modified twice (remember that the ++ operator modifies its
operand, unlike many other operators - it is an operator with a side
effect). Thus, this statement is undefined, and all bets are off.
Your premise that the ++ operator comes into action after the completion
of the statement is wrong. The standard guarantees that all side effects
are evaluated *before* the next sequence point.
Binand
--
Hanlon's Razor: Never attribute to malice that which can be adequately
explained by stupidity.
Bruce's Razor: Never attribute to stupidity that which can be adequately
explained by Microsoft funding.
-------------------------------------------------------
This SF.Net email is sponsored by BEA Weblogic Workshop
FREE Java Enterprise J2EE developer tools!
Get your free copy of BEA WebLogic Workshop 8.1 today.
http://ads.osdn.com/?ad_id=4721&alloc_id=10040&op=click