Sep 032012
 
 C, C++ Tags:  Add comments

What will be the output of the below code in C or C++ language?

int x = 0;

int a()
{
    x = 10;
    return 2;
}

int b()
{
    x = 20;
    return 3;
}

main()
{
    int y = a() + b();
    printf("%d", x);
}


The value of y will definitively be 5. Because function a() returns a constant value 2, and function b() returns a constant value 3.

But that’s not the question because what is getting printed is the value of x.

x is a global variable initialized to zero. Function a() sets the value of x to 10 and Function b() sets the value to 20.

In expression

y = a() + b();

The order in which function a() and b() will be called (which function gets called first) depends on the Order Of Evaluation of Operands for plus operator.

If plus operator evaluates its operand from Left to Right like below:

First a() will be called (which will set the value of x to 10)
Then, function b() will be called which will set the value of x to 20.
Hence, the final value of x will be 20.

If plus operator evaluates its operands from Right To Left as below:

First b() will be called (which will set the value of x to 20)
Then, function a() will be called which will set the value of x to 10.
Hence, the final value of x will be 10.

So, the final value of x depends on the order in which operands of plus operator are getting evaluated.

The Standard says, “Order of Evaluation of operands for plus operator is not defined“. This order has to be defined by the Compiler.

Hence the answer to the original question is “Not Defined” or “Compiler Dependent”.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)