Understanding the Difference Between Postfix and Prefix Operators

The built-in ++ and?operators can appear on both sides of their operand:

 int n=0;++n; // prefix ++n++; // postfix ++

You probably know that a prefix operator first changes its operand before taking its value. For example:

 int n=0, m=0;n = ++m; // first increment m, then assign its value to ncout << n << m; // display 1 1

In this example, n equals 1 after the assignment because the increment operation took place before m's value was taken and assigned to n. By contrast,

 int n=0, m=0;n = m++; // first assign m's value to n, then increment mcout << n << m; // display 0 1

In this example, n equals 0 after the assignment because the increment operation took place after m's original value was taken and assigned to n.

To understand the difference between postfix and prefix operators better, you can examine the disassembly code generated for these operations. Even if you're not familiar with assembly languages, you can immediately see the difference between the two?simply notice where the inc (increment) assembly directive appears:

 // disassembly of the expression: m=n++;mov ecx, [ebp-0x04] // store n's value in ecx registermov [ebp-0x08], ecx // assign value in ecx to minc dword ptr [ebp-0x04] // increment n;// disassembly of the expression: m=++n;inc dword ptr [ebp-0x04] // increment n;mov eax, [ebp-0x04] // store n's value in eax registermov [ebp-0x08], eax // assign value in eax to m
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

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