Why is the behavior different

A

ashish.dobhal

i=0;
printf("%d %d",i++,i);


I am writing the above piece of code and executing it on different
platforms (cygwin, solaris and linux). On cywin and linux the output is
"0 0", whereas on solaris it is "0 1". What the language specification
says about this case?


Thanks,
Ashish
 
J

Jakob Bieling

i=0;
printf("%d %d",i++,i);


I am writing the above piece of code and executing it on different
platforms (cygwin, solaris and linux). On cywin and linux the output
is "0 0", whereas on solaris it is "0 1". What the language
specification says about this case?

Afaik, it says its undefined, because you are reading and writing to
the same variable before reaching a sequence point. Just do not write
such code.

rhth
 
?

=?ISO-8859-1?Q?Stefan_N=E4we?=

i=0;
printf("%d %d",i++,i);


I am writing the above piece of code and executing it on different
platforms (cygwin, solaris and linux). On cywin and linux the output is
"0 0", whereas on solaris it is "0 1". What the language specification
says about this case?

5.2.2.8:

The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations
take effect before the function is entered. The order of evaluation of the postfix expression and the argument
expression list is unspecified.


Stefan
 
R

Rolf Magnus

Stefan said:
5.2.2.8:

The order of evaluation of arguments is unspecified. All side effects of
argument expression evaluations take effect before the function is
entered. The order of evaluation of the postfix expression and the
argument expression list is unspecified.

However, this is not really significant here. The more important part is:

5/4:

Between the previous and next sequence point a scalar object shall have its
stored value modified at most once by the evaluation of an expression.
Furthermore, the prior value shall be accessed only to determine the value
to be stored.
The requirements of this paragraph shall be met for each allowable ordering
of the subexpressions of a full expression; otherwise the behavior is
undefined.


Since i is used with the %d format specifier above, it must be an integer,
for which operator++ doesn't give a sequence point, but it does modify i,
which is read again for the second argument. In a function call, there is
only a sequence point after _all_ arguments have been evaluated, not
between them. So the behavior is not unspecified, but undefined.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top