Sunday, 30 November 2014

Pre Increment (++a) and Post Increment(a++)

I just learned something today... I think it is worth posting

there is a lot of difference between ++a and a++

even though they both get you same result when using with one variable But when we are using used inside an expression they both give the different results
like..

a = 2;
b = 3;
b = a++;
void setup(){
Serial.begin(9600);
Serial.println("b = a++");
Serial.print("a----> \t");
Serial.print(a);
Serial.print("b----> \t");
Serial.println(b);
Serial.println("");
b = ++a;

Serial.println("b = ++a");
Serial.print("a----> \t");
Serial.print(a);
Serial.print("b----> \t");
Serial.println(b);
Serial.println("");
}

void loop(){
}

post increment
if we did y = a++ , it first assign the a value to the y and increment the a value
if a = 2 ; after execution
the value of y = 2
and value of a = 3

pre increment
if we did y= ++a, it first increments the value of a and then assign the value to the y
if a = 7; after execution
the value of y = 8;
the value of a = 8;

it is also same for a-- and --a

and please note that a++ = ++a

No comments:

Post a Comment