Results 1 to 2 of 2

Thread: Want to know the working of this program.

  1. #1

    Want to know the working of this program.

    int main()
    int a=5,c;
    c = a++ + ++a + a++;
    printf("value of c= %d",c);
    return 0;

    How does the increment of a takes place in GCC compiler? The answer is 18 for c.

  2. #2
    Contributing Member
    Join Date
    Jun 2010

    Re: Want to know the working of this program.

    The behavior of "c = a++ + ++a + a++;" is undefined; the result will vary based on the compiler, optimization settings, surrounding code, etc.

    The problem is that the order in which each subexpression is evaluated and the order in which each side effect is applied is unspecified; there's no guarantee that each subexpression is evaluated left-to-right, and there's no guarantee that each side effect is applied immediately after the expression is evaluated. The compiler is explicitly given the freedom to reorder operations for optimization purposes, as long as they give the same result. Because of this, the behavior on attempting to modify the same object through the evaluation of more than expression without an intervening sequence point is explicitly left undefined by the language standard; the compiler isn't required to handle the expression in any particular way, so any result is considered "correct".

    Note that an expression like "a++ && a++" is well-defined, because the && operator forces left-to-right evaluation and introduces a sequence point; the left hand "a++" is fully evaluated and the side effect applied before the right hand "a++" is evaluated.

    If you really want to know how gcc evaluates the expression, look at the generated machine code (either by using the -S option or the -Wa,-aldh option). Just don't expect that to be consistent from program to program.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
About us
Applying for a job can be a stressful and frustrating experience, especially for someone who has never done it before. Considering that you are competing for the position with a at least a dozen other applicants, it is imperative that you thoroughly prepare for the job interview, in order to stand a good chance of getting hired. That's where GeekInterview can help.