-1

How the value of m is 2 after execution as i is postfix ?

int main()
{
   int i,m;
   int a[5]={8,10,1,14,16};
   i=++a[2];
   m=a[i++];
   cout<<i<<m;
   
   return 0;
}
iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 1
    `i=++a[2]` will get a reference to a[2] and set it to 2 before assigning it to i which will then have value 2. m will then be assigned value at `a[2]` which is 2 and then increase i again. This shows that writing code with pre-post increments can lead to hard to reason about code. Sometimes it is just better to split code into multiple lines and leave it up to the compiler to do the optimized thing. (which it will). Write readable code first, optimize later but only if needed. – Pepijn Kramer Nov 07 '22 at 03:52
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Nov 07 '22 at 06:35

1 Answers1

1

Your code can be broken down to following statements:

auto& temp = a[2]; // temp refers to 1
temp = temp + 1; // temp aka a[2] is now changed to 2
i = temp; // i = 2
m = a[i]; // *** m = 2 ***
i = i + 1; // i = 3

This is how m = 2 happens!

iammilind
  • 68,093
  • 33
  • 169
  • 336