Using incriment withing printf

So, I have something like this

1
2
3
  int a=0;
  char charArray[2][4]={"cat","dog"};
  printf("%s  %s",charArray[a],charArray[++a]);


I'm expecting this line of code to print out 'cat dog', but I'm getting 'dog dog'.
Does this seem right(or wrong) to anybody?
Thank you.
Can it be that printf first increments 'a', and than uses it in both calls to charArray?
When pushing parameters onto stack in reverse mode, the code charArray[++a] will be implemented first. Therefore, the output is just "dog dog".

You had better separate your code, like this :
1
2
printf("%s",charArray[a]);
printf("  %s", charArray[++a]);
Does this seem right(or wrong) to anybody?


It seems normal. You invoke undefined behavior and you get undefined behavior.

See:
http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points/4183735#4183735
Does this seem right(or wrong) to anybody?
It's wrong.

Can it be that printf first increments 'a', and than uses it in both calls to charArray?
yes, but the order of evaluation is not specified:

http://stackoverflow.com/questions/7112282/order-of-evaluation-of-operands
order of evaluation is only half the story: because the type of a is int and because ++a and a are executed without sequencing, the behavior is undefined.
Thank you, everybody.
Topic archived. No new replies allowed.