devxlogo

General Precedence

General Precedence

Question:
I am an engineer at GNB Technologies and have been programming for quite some time. Last week a friend of mine asked me an interesting question that stumped me. It’s very simple.

The code example is as follows:

#include int main (){	int x, num = 5;	num = ++num + num++;	cout 

The output is 13 and 12, even though the equation for variables num and x are the same. I have studied my precedence rules and the only explanation I have is that the compiler may be mistaking the + operator for a unary one, which would explain the result.

Could you help me resolve the reason for this discrepancy?

Answer:
Actually, the following expressions result in undefined behavior:

num = ++num + num++; x = ++num + num++;

Technically speaking, each of these expressions has several side effects within a single sequence point. According to the C++ standard, having more than a single side effect within a single sequence point is undefined. Therefore, the results are unpredictable.

The problem is that the compiler can apply the increment operations at any time, either before the assignment takes place or afterwards, so the results are at best compiler-dependent.

devx-admin

Share the Post: