1

There is a such question in my interview ,today.

#include <stdio.h>

int main(void) 
{
    char *s="123456790";
    printf("%c,%c",*(char *)((int *)s+++1),*s);
    return 0;
}

my answer is 5,1, but the Interviewer said it's 5,2! Of course, I knew the default calling convention in C is __cdecl,the argument-passing order is right to left, so I told to him about this. But he didn't believe it. Than we run it on VS2013. IT SHOWED 5,2!!!!!

Now,I come back home and try it again on ideone.THE ANSWER IS 5,1!!! http://ideone.com/sq6yRE WHY?! I am so confused about it .Who can help me,please?

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
sol H
  • 13
  • 2
  • 3
    The calling convention doesn't imply anything about the order that the arguments are *evaluated*, just the order in which they are *passed*. – Roger Rowland Apr 29 '14 at 06:29
  • [See here](http://stackoverflow.com/a/8785539/2065121) for a similar discussion. – Roger Rowland Apr 29 '14 at 06:35
  • 1
    Don't work for this company. Obviously they will give you unspecified tasks to work on... – Ferenc Deak Apr 29 '14 at 06:45
  • +1 for fritzone's suggestion. Unspecified tasks. – Mohit Jain Apr 29 '14 at 06:48
  • possible duplicate of [How does incrementation takes place in printf statement in C](http://stackoverflow.com/questions/13797279/how-does-incrementation-takes-place-in-printf-statement-in-c) – Michael Burr Apr 29 '14 at 08:26
  • This is more than just unspecified - it's undefined behavior because having `s++` and `*s` in the same expression without an intervening sequence point is UB. – Michael Burr Apr 29 '14 at 08:29
  • @MichaelBurr C99 6.5.2.2 Function calls 10. says _The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call_. – Mohit Jain Apr 29 '14 at 08:49
  • @MohitJain: but there is no sequence point between the `s++` and the `*s` expressions. – Michael Burr Apr 29 '14 at 08:51
  • @MichaelBurr Yes you are right. I misinterpreted. This line of code exhibits an undefined behavior. – Mohit Jain Apr 29 '14 at 08:53

1 Answers1

1

In C the order of evaluation of function argument is unspecified.

Code written below

int main()
{
  printf("%d %d\n", printf("Hi\n"), printf("Hello\n"));
  return 0;
}

May produce either

Hello
Hi
3 6

or

Hi
Hello
3 6

as output.

And neither you nor your interviewer should question why, how etc.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • Thanks,I see it,now. C99 6.5.2.2 Function calls 10.The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call. – sol H Apr 29 '14 at 08:08