-2

Having an issue with C and understanding how the compiler is processing this code

#include <stdio.h>

int j=0;

int main(int argc, char *argv[]){
printf("%d %d %d %d %d\n",j++, j*5, j++,  j++,  j);
}

Hi okay so basically i am trying to understand what is going on here?

when i compile and run i get this as a result

2 10 1 0 0

it is not clear to me what exactly the compiler is doing, why does the number change like that? which one is being done first and why does some report a 0 while other 2 and none reports a 3?

yukapuka
  • 87
  • 1
  • 2
  • 8
  • 1
    Please [edit] the title of your question to something that describes the actual problem. "Hard time understanding this" has no relevance, and it will be absolutely meaningless to any future reader here who sees it in a search result. Thanks. – Ken White Aug 23 '14 at 00:14
  • Order of evaluation of arguments to a function are not specified. – BLUEPIXY Aug 23 '14 at 00:16
  • 1
    I believe this is undefined behavior, so anything could happen. In this particular case, the arguments are being evaluated from right to left. – red_eight Aug 23 '14 at 00:17
  • @red_eight 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._ – BLUEPIXY Aug 23 '14 at 00:29

1 Answers1

0

The entries are being processed back to front. I'm not 100% but I'd think that the order of processing of arguments to a printf() statement is not set so the result is not predictable (from compiler to compiler).

Jiminion
  • 5,080
  • 1
  • 31
  • 54