Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases i++ and ++i can refer to the same value? [duplicate]

Tags:

c

increment

Why is i++ and ++i same in the following code?

#include <stdio.h>  

int main()  
{  
    int i=5;  

    while(1)  
    {  
        i++;                  /*replacing i++ by ++i also gives 6*/  
        printf("%d",i);  
        break;  
    }  

    return 0; 
}  

The output is 6. I learnt that the increment operator i++ has its value the current value of i and causes the stored value of i to be incremented.But i's value is displayed as 6 though the current value of i is 5. Replacing i++ by ++i also gives the same value 6. Why is i++ and ++i same in this case and why output is 6 though initial value is 5.

like image 644
user3124361 Avatar asked Jan 22 '26 22:01

user3124361


1 Answers

The order of execution is sequential.

i++ or for that matter ++i is a single instruction to be executed at that sequence point, with i's value not being used anywhere at that instruction, so it doesn't really matter.

If you do replace printf("%d",i); with printf("%d",i++); or printf("%d",++i); things will be much different.

EDIT: I also discovered something that is fairly useful to know. In C and C++, the prefix unary operator returns an lvalue, in contrast to the postfix unary operator, so if you want to, for example, decrement i twice, then

(i--)--; // is illegal

whereas

(--i)--; // is perfectly legal and works as intended.
like image 194
NlightNFotis Avatar answered Jan 25 '26 13:01

NlightNFotis