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
This is a discussion on Problem understanding simple increment operation within the C Programming forums, part of the General Programming Boards category; Code: int i=5,j; j=++i + ++i + ++i; printf("%d",j); //22 i=5; j=i++ + i++ + i++; printf("%d",j); //19 Shall not ...
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
Last edited by Avenger625; 01-27-2013 at 12:18 PM.
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
Code - functions and small libraries I use
__________________________________________________ __________________________________________________ ______________
It’s 2013 and I still use printf() for debugging.
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 -> Post and Pre Increment
Make careful note of the wonderful variety of answers you can get from undefined behaviour.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.