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 << num << endl;	num = 5;	x = ++num + num++;	cout << x << endl;	return 0;}

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.

See also  5 Ways to Improve Customer Experience
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist