General Precedence

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?

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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.