Why is the behavior different

Discussion in 'C++' started by ashish.dobhal, Apr 4, 2006.

  1. i=0;
    printf("%d %d",i++,i);


    I am writing the above piece of code and executing it on different
    platforms (cygwin, solaris and linux). On cywin and linux the output is
    "0 0", whereas on solaris it is "0 1". What the language specification
    says about this case?


    Thanks,
    Ashish
     
    ashish.dobhal, Apr 4, 2006
    #1
    1. Advertisements

  2. Afaik, it says its undefined, because you are reading and writing to
    the same variable before reaching a sequence point. Just do not write
    such code.

    rhth
     
    Jakob Bieling, Apr 4, 2006
    #2
    1. Advertisements

  3. 5.2.2.8:

    The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations
    take effect before the function is entered. The order of evaluation of the postfix expression and the argument
    expression list is unspecified.


    Stefan
     
    =?ISO-8859-1?Q?Stefan_N=E4we?=, Apr 4, 2006
    #3
  4. ashish.dobhal

    Rolf Magnus Guest

    However, this is not really significant here. The more important part is:

    5/4:

    Between the previous and next sequence point a scalar object shall have its
    stored value modified at most once by the evaluation of an expression.
    Furthermore, the prior value shall be accessed only to determine the value
    to be stored.
    The requirements of this paragraph shall be met for each allowable ordering
    of the subexpressions of a full expression; otherwise the behavior is
    undefined.


    Since i is used with the %d format specifier above, it must be an integer,
    for which operator++ doesn't give a sequence point, but it does modify i,
    which is read again for the second argument. In a function call, there is
    only a sequence point after _all_ arguments have been evaluated, not
    between them. So the behavior is not unspecified, but undefined.
     
    Rolf Magnus, Apr 4, 2006
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.