0

I am executing this code, but i am not able to get why the 6th part is showing answer 2 instead of 1.

#include<stdio.h>

int main()
{
    int x[3][5] = {
                    {1,2,3,4,5},
                    {6,7,8,9,10},
                    {11,12,13,14,15}
                    };
    int *n =  (int *)&x;

    printf("1) %d\n2) %d\n3) %d\n4) %d\n5) %d", *(*(x+2)+1), *(*x + 2)+5, *(*(x+1)), *(*x +2)+1, *(*(x+1) +3) );
    printf("\n6) %d\n7) %d\n8) %d\n9) %d\n10) %d\n", *(n+0), *(n+2), (*(n+3) + 1), *(n+5) +1, ++*n);                
}

Output of the code is :

1) 12
2) 8
3) 6
4) 4
5) 9
6) 2 // i am not getting this.
7) 3
8) 5
9) 7
10) 2

According to me the answer of part 6th must be 1. Why this is so?

harshit batra
  • 75
  • 1
  • 13
  • 3
    The order in which function parameters is evaluated is not specified, so using the pre-increment operator `++*n` is just asking for trouble. – user3386109 Jan 28 '17 at 04:45
  • What is the reason for this unusual behavior? According to other answers it is evaluating from left to right. @user3386109 – harshit batra Jan 28 '17 at 04:50
  • Then the other answers must be talking about the behavior of a specific compiler. The C standard says the arguments can be evaluated in any order. – user3386109 Jan 28 '17 at 04:51
  • But i have learnt that they can evaluate either from left to right or from right to left. @user3386109 – harshit batra Jan 28 '17 at 05:04
  • 2
    @harshitbatra: That's incorrect. It is not guaranteed to make any sense at all, if you ignore rules about sequence points. So it's possible that it won't make sense no matter what order you put it in. The only way to get predictable results is to fix the errors in your code. – Dietrich Epp Jan 28 '17 at 05:09
  • so i must right separate expressions (or individual printf) for each of them, to get predictable results. Is it so? @DietrichEpp – harshit batra Jan 28 '17 at 05:14
  • You just need to separate out expressions like `++*n` from `*(n+0)`, which is equivalent to `*n`. You can't use `++*n` and `*n` in the same expression. – Dietrich Epp Jan 28 '17 at 06:06
  • 1
    This kind of thing can surprise people, it's a little less surprising if you know how optimizing compilers work. – Dietrich Epp Jan 28 '17 at 06:08

0 Answers0