About Me

My photo
Bangalore, Karnataka, India

Sunday, August 20, 2006

What is the problem with this C++ code ?

What is the problem with the code below?

class FooBar
{
public:
FooBar(int val): _val(val) {};
~FooBar() {};

void Foo(int val)
{
_val += Bar(val);
};

int Val() { return _val; };

private:
int Bar(int val)
{
_val = val;
return _val;
};

int _val;
};

int main()
{
FooBar fb(42);
fb.Foo(1);

int val = fb.Val();

return 0;
}

This one of the very subtle problem facing a C++ developer.
The problem lies in the code

_val += Bar(val);

In short the evaluation of this expression is dependent on a compiler implementation. So based on whether you compile it using gcc or someother compiler you might get either 43 or 2.

The question is why is it compiler dependent ?
The reason is that there are no sequence points within the expression += .

Hence the value of _val in the expression depends on whether the compiler uses the value of _val after the side effect of Bar(val) or does it use the value before the Bar(val).

As per the C++ specification the only guarantee is that all side-effects of a previous evaluation shall be complete before the sequence point for the expression is evaluated. But within a single sequence point, the side effects can take place at any time.

hence some compiler might implement this as

int temp = Bar(val);
_val = _val + temp;

hence here the value of _val is taken as 1 and hence it becomes 2 after the expression is evaluated.

While some other compiler might implement this as,

int temp = 0;
_val = _val + (temp = Bar(val));


hence as we see within the sequence point the side-effect is completed, but when it happens is not specified by the C++ standard. Now is this a problem in the standard is a debatable question. I am not sure how JAVA deals with such scenarios ?

No comments: