If n has 3, then what the statement a[++n]=n++ does?

If n has  3, then the statement a[++n]=n++;

  1. assigns 3 to a[5]
  2. assigns 4 to a[5]
  3. assigns 4 to a[4]
  4. what is assigned is compiler dependent

Prashant Sharma prashantsharma 17 Apr 2017 05:50 pm
@shweta, the the final answer is compiler dependent.

Look, here:
for the variable "n".There are two things:
1) Use "n" as the index of the array a.(After doing ++n)
2) Increment the the value of "n" by 1.(by doing n++)

Now, the confusion is :
whether to use the value of "n" before it is modified (incremented by doing n++) as the index, or after it . Different compilers will try to solve this confusion, by doing something like:
a) doing ++n on the value of "n" first (to be used as the index)
b) doing n++ first, and then ++n to calculate the index

This is undefined behaviour, and will depend on how a particular compiler handles such situation.
for more examples on undefined behaviour,
refer: https://en.wikipedia.org/wiki/Undefined_behavior [see the example section].

shweta shweta1920 23 Apr 2017 08:34 pm

if undefined wasnt given in the option then ? which u think would hv been the answer?

versha mishra vershamishra 16 Oct 2017 02:08 am

@shweta1920 if undefined wasnt given in the option then option 3 would be the ans.