Shall not it give 21 and 18 respectively?????Code:
int i=5,j;
j=++i + ++i + ++i;
printf("%d",j); //22
i=5;
j=i++ + i++ + i++;
printf("%d",j); //19
Printable View
Shall not it give 21 and 18 respectively?????Code:
int i=5,j;
j=++i + ++i + ++i;
printf("%d",j); //22
i=5;
j=i++ + i++ + i++;
printf("%d",j); //19
Switching on the warnings can help.
This results to undefined behavior and should never be followed by any programmer. But I guess, you found that while learning. (so do I one year ago (or two probably)).
I got 22 and 15 :PCode:linux05:/home/users/std10093>gcc -Wall px.c -o px
px.c: In function 'main':
px.c:4: warning: operation on 'i' may be undefined
px.c:4: warning: operation on 'i' may be undefined
px.c:7: warning: operation on 'i' may be undefined
px.c:7: warning: operation on 'i' may be undefined
The important thing to remember with expressions is that the order of evaluation is not specified. So for example if you write
Then the order in which EXPRA, EXPRB and EXPRC is evaluated is not fixed. It is arbtirary. Therefore, you should not use any expressions here where you really are depending on their side effects. A side effect is something that happens as the result of an expression being evaluated (like incrementing a variable, for example).Code:j = EXPRA + EXPRB + EXPRC;
So basically, there is not any correct answer for what will happen for the expressions you gave. Usually the best idea is to use increments either all by themselves, or to use them in very restricted situations, for example
is just fine. It puts foo into myArray at position i, and then conveniently increments i for you afterwards.Code:myArray[i++] = foo;
The example you gave contains several lines of code that result in undefined behavior. There are lots of similar examples with discussion in the following section of the C-FAQ: Expressions.
Check my example here -> http://cboard.cprogramming.com/c-pro...increment.html
Make careful note of the wonderful variety of answers you can get from undefined behaviour.