increment and decrement

here is a snippet

void main()
{
int a=6;
a*=++a;
printf("a=%d",a);
}

output
42

i m confused how does the increment and decrement operator work.
a*=++a;

This is undefined behavior (it might not necessarily result in 42). You cannot modify a variable multiple times in the same statement.
As far as I know according to the new C++ Standard the result should be equal to 49. According to C++ Standards before 2011 the code has undefined behaviour.
Last edited on
a*=++a;
you multiplied (a) by itself but not stored to (a) yet then (a) is added then stored to (a). The result of the operation before the equal sign is not stored till the operation after the = sign is performed. It is also equivalent to a = a * a + a;

correction:
Yes, that should be 49 as (a) would be incremented and stored then multiplied to itself..
Last edited on
Topic archived. No new replies allowed.