i++ and ++i operator

anukalp

Jul 28, 2018
35
Joined
Jul 28, 2018
Messages
35
What is the difference between ++i and ++i, both are increment, but i am confused with their operations.

any one kindly make me understand how they both works and what is the output, the output is same i have tried.

Code:
int main()
{   
   int x = 10;
   x++;
    printf("x is %d", x);
    return 0;
}
x is 11

and

Code:
int main()
{   
   int x = 10;
   ++x;
    printf("x is %d", x);
    return 0;
}

x is 11
 

HellasTechn

Apr 14, 2013
1,579
Joined
Apr 14, 2013
Messages
1,579
I know little about C language but i think that it is exactly the same thing.
 

Hopup

Jul 5, 2015
253
Joined
Jul 5, 2015
Messages
253
It is same thing in this context but it can be different thing when assigning variable for example.
 

Hopup

Jul 5, 2015
253
Joined
Jul 5, 2015
Messages
253
It would cause different result in example like this:

A = 1;
B = ++A;

This results B = 2, A = 2

A = 1;
B = A++;

This results B = 1, A = 2
 

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
If you study PDP-11 assembly language you'll see where many of C's features come from.

The addressing modes of auto increment/decrement, deferral, and indirection provide 1 instruction implementation of many of C's arithmetic and pointer operations for a certain set of variable types. The various flags set after arithmetic operations and the operation of the compare instruction provide further insight into aspects of the C language.

In many ways C reflects the desire to write low level code more easily on the PDP-11 predecesors and this closely reflects the architecture of this machine.

Many years ago, as a lark, I wrote a couple of macros for the PDP-11 assembler which translated a small subset of simple C statements into assembler.

The chicken and egg / pulling one's self up by the bootstraps implementation of the C compiler had it's early roots in something like this.
 
Last edited:

anukalp

Jul 28, 2018
35
Joined
Jul 28, 2018
Messages
35
It would cause different result in example like this:

A = 1;
B = ++A;

This results B = 2, A = 2

A = 1;
B = A++;

This results B = 1, A = 2

This gives
Code:
int main(void)
{
   int a = 0;
   int b = a++;
 
   printf("Value of b is %d \n", b);
 
   printf("Value of a is %d \n",a);
 
   return 0;
}
Value of b is 0
Value of a is 1

and

Code:
int main(void)
{
   int a = 0;
   int b = ++a;
 
   printf("Value of b is %d \n", b);
 
   printf("Value of a is %d \n",a);
 
   return 0;
}

Value of b is 1
Value of a is 1

any reason When do you use ++a or a++ in program ?
 

Hopup

Jul 5, 2015
253
Joined
Jul 5, 2015
Messages
253
Like bluejets stated, it is about the order how the code is processed. Like you can see in my example, when the increment is before the A, it is processed but when its after it is not processed before the creation of new variable.
 
Top