# Problem understanding simple increment operation

• 01-27-2013
Avenger625
Problem understanding simple increment operation
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 it give 21 and 18 respectively?????
• 01-27-2013
std10093
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)).

Code:

```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```
I got 22 and 15 :P
• 01-27-2013
c99tutorial
The important thing to remember with expressions is that the order of evaluation is not specified. So for example if you write

Code:

`j = EXPRA + EXPRB + EXPRC;`
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).

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

Code:

`myArray[i++] = foo;`
is just fine. It puts foo into myArray at position i, and then conveniently increments i for you afterwards.
• 01-27-2013
anduril462
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.
• 01-27-2013
Salem
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.