C’s secret operator: goes to

Consider the following code:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
 
using namespace std;
 
int main()
{
	int n = 10;
 
	while(n --> 0)
		cout << "n: " << n << endl;
}

Should it compile? If your answer is yes, what should be its output?

Spoiler warning: if you want to try to answer it, don’t look below the image following this paragraph.

an image should be herePicture 1. Placeholder.


It does compile and it outputs numbers from 9 to 0.

n: 9
n: 8
n: 7
n: 6
n: 5
n: 4
n: 3
n: 2
n: 1
n: 0

How does it work?

It doesn’t. At least, it doesn’t work as a separate operator, as there’s no such thing as operator-​->. It’s just a trick on your eyes, the compiler doesn’t see any difference between n -​-> 0 and n-​- > 0 or even (more or less) 0 < n-​-.

Why?

While most use coding rules that forbid writing such code, I’m sure no one will deny that the intent behind such loop condition is clear. As for the reason to loop down to zero: on some platforms (x86 being the most prominent one of the bunch), assembly decrement operation will set required flags to allow conditional jump (jz or jnz on x86) without wasting processor time on another comparison.

2 thoughts on “C’s secret operator: goes to

Leave a Reply

Your email address will not be published.