Printf and ++ operator

Possible duplicates:
printf ("% d% d% d \ n", ++ a, a ++, a) output problem
The procedure for evaluating parameters before calling a function in C

#include<stdio.h> main() { int a=10; printf("\n %d %d", a, a++); //11 10 a=10; printf("\n %d %d", a++, a); //10 11 a=10; printf("\n %d %d %d ", a, a++,++a); //12 11 12 } 

after running this, I got the result indicated in the comments. as far as I know, the first result is expected, because printf runs from right to left, but cannot understand the second and third

+6
c
source share
5 answers

Nothing happens right-to-left in evaluating function arguments. When function arguments are evaluated, the evaluation order is unspecified and there are no sequence points between the evaluation of the individual arguments. This means that there is no temporary order in this process. Arguments can be evaluated in any order, and their evaluation process can be intertwined in some way.

However, your code suffers from even worse problems. All three operators that invoke printf create undefined (UB) behavior because they either try to change the same object twice ( a ) without a sequence point between the modifications (third call), or they try to change the object and read it for independent goals (first and second challenges). Thus, it is too early to mention the evaluation procedure. Your code behavior is undefined.

+8
source share

None of the exits can truly qualify as unexpected. All arguments of the function are evaluated before entering the function itself, but the order of their evaluation relative to each other is not defined, therefore all these results are allowed. Officially, your last one (having two separate instances of increment a ) has undefined behavior, so it doesn't need to do anything at all.

+3
source share

You invoke undefined behavior, referencing "a" and "a ++" in the argument list.

It is not determined which order of arguments is evaluated. Different compilers can choose different orders. One compiler can select different orders at different times.

Do not do this!

+3
source share

Functional parameters are not evaluated in a specific order in C. Therefore, you cannot tell in advance whether a or a++ will be evaluated when printf called.

See Procedure for evaluating parameters before calling a function in C

+1
source share

++ a means incrementing the first and then returns the expression. (a changes, and the expression evaluates to + 1)

a ++ means evaluating a (so erm, a) and then increment it. Thus, a is passed, but then the value of a then (that is, later) changes to a + 1.

0
source share

All Articles