Click here to Skip to main content
15,899,314 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<stdio.h>
int main()
{
    int a=2;
    printf("%d,%d",a++,++a);
    return 0;
}

the output of this is 3,4
C++
#include<stdio.h>
int main()
{
    int a=2;
    printf("%d,%d",++a,a++);
    return 0;
}

the output of this is 4,2
as a is to be printed first 2 has to be printed in first case and then int i is incremented twice so 4 should be printed next.Is there any rule for printf while executing.
thanks.
Posted
Updated 10-Feb-15 2:57am
v2

The order in which C function parameters are evaluated isn't strictly defined.
You can get the second case to print 3, 2 and the first to print 3, 3 depending on the compiler used.
 
Share this answer
 
Lessons to learn:

  1. In C/C++, the sequence of evaluating function arguments is unspecified.
  2. If any variable in an expression has a side effect, it should be the only instance of that variable in that expression.
  3. If you don't know for sure if function name is in fact a macro name, don't do any side effects in the function call arguments.

Things not to do in C/C++:
C
x = a[x] + x++; // unspecified sequence of evaluation
v[x] = ++x; // do you know for sure which is first incremented?
v = max(x++, ++y); // double side effect if "max" is a macro: #define max(a,b) (a)>(b)?(a):(b)

Cheers
Andi
 
Share this answer
 
The way you get values with 'side effetct' in a function parameter's list depends on how they are used during call preparation.
As a rule of thumb, considering that C consume parameters from right to left the result you got is exactly what you should have expected:
- Get rightmost parameter and pass it, then increment it (postincrement)
- Get next parameter, preincrement it then pass as parameter.
This seems to solve all the problems :) ,but is not true :(
Is not true because this is not guarantee, infact C11 standard states, at §6.5.2.2 sentence 10 that the parameters evaluation sequence is undefined. This decision come from the considration that fixing the order of evaluation of parameters would have limited the optimization of code. I.e. If evaluating the parameters in a different sequence would allow a better code optimization it can be done.
The impacting point is that all 'side effects' of parameters have to be carefully considered by the programmer, and as best solution is preferrable to have no 'side effects' from functions parameters. :(
N.B. I said how function consumes parameters opposed to the term 'pushed' generally used in past because the actual methodology is dependent from processor: win64 always pass parameters through registers (__fastcall).
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900