By GManNickG

2009-10-29 06:57:45 8 Comments

After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4.

Here's the code:

#include <stdio.h>
int main()
    int x = 10;
    while (x --> 0) // x goes to 0
        printf("%d ", x);


9 8 7 6 5 4 3 2 1 0

I'd assume this is C, since it works in GCC as well. Where is this defined in the standard, and where has it come from?


@RageZ 2009-10-29 07:00:19


#include <stdio.h>

int main(void) {
  int x = 10;
  while (x-- > 0) { // x goes to 0
    printf("%d ", x);
  return 0;

Just the space makes the things look funny, -- decrements and > compares.

@Neeraj Bansal 2020-07-06 11:28:09

Here -- is unary post decrement operator.

 while (x-- > 0) // x goes to 0
     printf("%d ", x);
  • In the starting condition will evaluate as
    (x > 0) // 10 > 0
  • Now because condition is true, it will go into loop with decrement value
    x-- // x = 9
  • That's why first printed value is 9
  • And so on. In the last loop x=1 so condition is true. as per unary operator value changed to x = 0 at the time of print.
  • Now, x = 0 which evaluates the condition (x > 0 ) as false and while loop get exit.

@Ankit Mishra 2020-06-15 18:15:17

This --> is not a operator at all. We have operator like -> but not like -->. It is just a wrong interpretation of while(x-- >0) which simply means x has post decrement operator and this loop will run till it is greater than Zero.

Another simple way of writing this code would be while(x--) while loop will stop whenever it gets false condition and here there is only one case i.e 0. so it will stop when x value is decremented to `Zero'.

@Nick Calabrese 2020-06-12 03:02:45

When the compiler scans the input file for tokens it chooses the first and longest valid token which is defined by a regular expression. This is why "--" is lexed as the decrement operator and not two minus signs ("-") next to each other. Some tokens need to be separated by specific characters (often whitespace) and sometimes they don't. That's why "5+5" is just as valid as "5 + 5"; the tokens don't require any specific delimeters because "5+" isn't a valid token in C++. In your specific question the first longest token available was "--" so that was chosen instead of "-" or "->" which respectively are not the longest and not the first valid tokens. So as a result the scanner saw "--" and created a decrement token, then the greater than sign and created its accompanying token.

@Jay Riggs 2009-10-29 07:00:13

It's equivalent to

while (x-- > 0)

x-- (post decrement) is equivalent to x = x-1 so, the code transforms to:

while(x > 0) {
    x = x-1;
    // logic
x--;   // The post decrement done when x <= 0

@uliwitness 2018-10-16 16:03:48

This is not quite right. The value of x inside the loop body is different in the second case. The assignment statement in your example should be above the logic for it to be equivalent. Postfix -- subtracts 1, but the comparison will happen with the value from before the subtraction.

@Taco 2019-01-02 19:36:20

@uliwitness These are truly equivalent. It would be wrong if prefix were being used: 0 >-- x In this case x is decremented prior to the logic. In postfix, the logic is executed prior to the decrement and thus both samples are equivalent. Feel free to write them up in a Console and test them.

@Caesar 2019-01-15 14:56:57

They're still not equivalent. After the first loop, x is -1 (or overflown in case it is unsigned), after the second, it is 0. (Assuming that x starts out non-negative, neither loop modifies x or breaks or…)

@S.S. Anne 2020-03-16 19:25:41

while(x=x-1,x+1 > 0) is equivalent.

@Elliott 2020-03-20 13:46:00

@Shebham, Here's a counter example: if x starts as 0, under the original loop it would exit as -1, with your version it would remain zero. So they're not equivalent.

@Jesper 2020-05-14 13:22:10

x-- is not equivalent to x = x-1. They're only equivalent when the expression x-- is in a separate statement and you don't use the value. The value of x-- is x, and the value of x = x-1 is x-1. Only --x is logically equivalent to (x = x-1). So this answer is messy and likely to confuse the beginner. And, mind you, it is written for the absolute beginner, as it replaces x-- with x = x-1 to explain x--.

@unsynchronized 2012-01-18 11:18:08

Or for something completely different... x slides to 0.

while (x --\
               > 0)
     printf("%d ", x);

Not so mathematical, but... every picture paints a thousand words...

@Hogan 2012-03-10 04:37:36

@mafutrct - As I remember it \ in C just appends the next line as if there was not a line break. The \s here basically do nothing.

@Felype 2013-05-20 18:10:06

@mafu the '\' character tells the compiler that the current line continues in the next line and so the compiler should merge both lines and compile as one. 'while (x -- > 0)' will run until x is equals to -1. But, the way he makes the indentations makes it look like x is sliding to zero. 'While x slides to 0...'

@Jules 2013-07-13 09:23:17

IIRC, K&R C allowed whitespace between the '-'s in the decrement operator, in which case you could have the backslashes in the middle of it, which would look even cooler. :)

@GL2014 2016-08-12 19:05:24

A backslash is an escape character, you are escaping the newlines using \<enter> so that the only thing the compiler sees is white space which is essentially removed, so this is equivalent to (x -- > 0)

@unsynchronized 2016-09-10 11:36:46

@ArnavBorborah it's an old expression meaning why waste words when a picture does a better job , used as a joke in this context. (there are in fact 2 keywords while and printf )

@demonkoryu 2017-10-27 10:00:48

Ah yes, the obscure slide operator. How could I forget!

@Fred Larson 2018-04-30 14:41:10

@unsynchronized: printf is not a keyword in C.

@totten 2018-05-29 09:28:09

@Hogan backslash "\" doesn't tell compiler to append next line in the current one. It just escapes line ending \n.

@Hogan 2018-05-31 16:23:33

@totten -- I guess you have a point - in fact no "appending" will happen -- it will just be ignored by the lexer and parser. Of course, from an abstract and end user point of view it is the same as an appending. But you make an excellent point about it not being the "same thing."

@Artelius 2020-08-21 01:20:06

Removing the first backslash would actually make it look more like a slide

@Clockwork 2020-10-18 09:36:38

I am honestly surprised that this stands as an answer at all. Not only does it lack any explanation as to why it works, but it's also mocking the question for not understanding what's going on. This is painful.

@Kirill V. Lyadvinsky 2009-10-29 08:38:08

That's a very complicated operator, so even ISO/IEC JTC1 (Joint Technical Committee 1) placed its description in two different parts of the C++ Standard.

Joking aside, they are two different operators: -- and > described respectively in §5.2.6/2 and §5.9 of the C++03 Standard.

@Kalana 2019-09-23 12:39:00

(x --> 0) means (x-- > 0)

  1. you can use (x -->)
    output -: 9 8 7 6 5 4 3 2 1 0

  2. you can use (-- x > 0) It's mean (--x > 0)
    output -: 9 8 7 6 5 4 3 2 1

  3. you can use
     x > 0)

output -: 9 8 7 6 5 4 3 2 1

  1. you can use
   x --> 0)

output -: 9 8 7 6 5 4 3 2 1 0

  1. you can use
   x --> 0

output -: 9 8 7 6 5 4 3 2 1 0

  1. you can use also

output -: 9 8 7 6 5 4 3 2 1 0

likewise, You can try lot of methods to execute this command successfully

@Zohaib Ejaz 2017-05-28 20:10:34

In the conventional way we would define a condition in the while loop parenthesis () and a terminating condition inside the braces {}, but --> defines both at once.

For example:

int abc(void)
    int a = 5
    while((a--) > 0) // Decrement and comparison both at once
        // Code

This decrements a and runs the loop while a is greater than 0.

Conventionally, it would be like:

int abc(void)
    int a = 5;
    while(a > 0)
        // Code

Both ways, we do the same thing and achieve the same goals.

@v010dya 2017-07-14 19:07:40

This is incorrect. The code in the question does: 'test-write-execute' (test first, write new value, execute the loop), your example is 'test-execute-write'.

@Kotauskas 2019-05-12 10:59:49

@v010dya Fixed the answer, now it's test-write-execute as in the question, thanks for pointing out!

@S.S. Anne 2019-06-15 19:36:17

@VladislavToncharov Your edit was still wrong. See mine.

@Charles Salvia 2009-10-29 07:00:09

--> is not an operator. It is in fact two separate operators, -- and >.

The conditional's code decrements x, while returning x's original (not decremented) value, and then compares the original value with 0 using the > operator.

To better understand, the statement could be written as follows:

while( (x--) > 0 )

@Charles Salvia 2009-10-29 07:14:52

Then again, it does kind of look like some kind of range operator in that context.

@Charles Salvia 2009-10-29 08:35:27

Saying that x is post-decremented and then compared to 0 is the same as saying x is decremented after being compared to 0

@Sajad Bahmani 2009-11-18 12:54:07

I think first compare then decrement --x>0 first decrement then compare

@Johannes Schaub - litb 2010-01-30 17:42:40

I don't think it's the same. I think the word "then" implies there is an order (after post decrementing, x's value is one less). I think one can say "You're post decrementing x and then comparing its old value and 0 ..." to make it clearer. But this is nitpicking anyway. We all know what is meant.

@Andrew Ring 2013-11-19 16:48:14

Note that when you exit the while loop, x will contain -1, not 0. This is because the loop breaks when the current value is 0 or less and this is then decremented. Additionally, you are approaching 0 from "above" so you will reach 0, decrement and break. If x begins below 0, it will simply decrement and never enter the loop.

@zhengtonic 2014-03-13 13:28:56

the first thing that came in my mind was "what? is this some fancy c++ syntactic sugar thing to express ptr** ", but than there was the 0 behind it ...

@GMasucci 2014-05-23 13:42:13

The notation --> is often used by the more mathematical purist programmers, I have even heard it termed as "tends to" as that is effectively the behaviour it is being used for in many cases. In regards to --) that's the vertical biclops smiley.... ;D or predecrement banana, whichever you prefer :D

@August Karlstrom 2014-07-02 12:18:29

IMHO "to better understand, the statement could be as follows:" while (x > 0) { x--; printf("%d ", x); } or even better: a for loop.

@Andy_A̷n̷d̷y̷ 2015-11-01 09:39:54

The > 0 is not needed since the while loop will stop at x=0

@Jay Schauer 2015-12-26 21:36:59

That's interesting that it isn't an operator, but is there a name for it? Or do we just have to call it the arrow thingy?

@paxdiablo 2016-02-15 01:28:00

The name for it, @Jay, is bad programming style :-) This is evidenced by the fact the question was asked in the first place. It makes much more sense to textually bind operators to the thing they're operating on rather than something unrelated, so while (x-- > 0) would be more apt. It also makes it more obvious what's going on (at least in a fixed-font editor) meaning that the parentheses in this answer would not be necessary.

@paxdiablo 2016-02-15 01:30:54

Note that I'm not saying you have to leave out spaces between operators and operands (like a+b) just that they shouldn't give unbalanced preference (a+ b or a +b) or incorrect preference (as in the question, or char* x, y (that's a char pointer and a char so would be better written as char *x, y or `char y, *x) to avoid possible confusion).

@tyger 2016-07-23 15:52:38

@AugustKarlstrom You are wrong cause in case of x == 0 while (x > 0) {x--;} gives you x == 0 but while (x-->0){} gives you x == -1

@August Karlstrom 2016-07-24 13:02:57

@tyger You're right, and this illustrates how error prone expressions with side-effects are.

@cvanbrederode 2017-01-23 21:06:55

I would say that a "name" for this would be "greedy parser". C++ keeps grabbing characters from the stream as long as it results in something it understands. That's why this comes out as -- and >, as opposed to - and ->.

@visualex 2017-03-21 08:03:24

Also works in PHP, you cannot speed it up with a double -- unfortunately as it gives a parse error.

@lenerdv 2020-03-09 10:27:06

well, i guess ++< would also work, if the goal was the opposite

@Garry_G 2016-10-27 15:09:20

Why all the complication?

The simple answer to the original question is just :

#include <stdio.h>
int main()
    int x = 10;
    while (x > 0) 
        printf("%d ", x);
        x = x-1;

Does the same thing. Not saying you should do it like this, but it does the same thing and would have answered the question in one post.

The x-- is just shorthand for the above, and > is just a normal greater-than operator. No big mystery!

There's too much people making simple things complicated nowadays ;)

@pix 2016-10-27 15:32:01

This question is not about complications, but about ** Hidden Features and Dark Corners of C++/STL**

@Öö Tiib 2017-05-13 09:30:30

The program here gives different output than original because x here is decremented after printf. That demonstrates well how "simple answers" are usually Incorrect.

@Anthony 2017-12-15 18:33:22

The OP's way: 9 8 7 6 5 4 3 2 1 0 and The Garry_G way: 10 9 8 7 6 5 4 3 2 1

@CITBL 2019-01-05 17:05:49

It doesn't do the same thing. Move your x=x-1 before printf then you can say "it does the same thing".

@doc 2014-12-28 00:32:03

x can go to zero even faster in the opposite direction:

int x = 10;

while( 0 <---- x )
   printf("%d ", x);

8 6 4 2

You can control speed with an arrow!

int x = 100;

while( 0 <-------------------- x )
   printf("%d ", x);

90 80 70 60 50 40 30 20 10


@Bhuvanesh 2015-01-19 12:13:36

which operating system, this type of output generated, i am using a ubuntu 12.04 in that i had a error message

@doc 2015-01-19 13:03:53

@Bhuvanesh operating system is irrelevant. This is simple C++ code (using printf(), because OP uses it), which should compile everywhere, so it must be your error.

@Blimeo 2015-03-26 02:41:40

Though it should be obvious, to everyone new to C++ reading this: don't do it. Just use augmented assignment if you have need to increment/decrement by more than one.

@Samuel Danielson 2016-03-09 21:54:16

Zero with "lasers". while( 0 > - - - - - -- -- -- -- -- ---------- x ) ... same output.

@phord 2016-03-23 16:45:06

Nice try, but --x does not return an lvalue, so --(--x) does not compile.

@doc 2016-03-24 10:43:16

@phord are you sure it does not compile? -->

@phord 2016-03-25 14:58:46

@doc It compiles in c++, but not in c.

@Xiè Jìléi 2016-05-30 01:38:26

I've just checked that, both opposite goes to operator and the laser BIU~~ operator are just not so fast, cuz they can't be optimized by gcc!

@Chipster 2019-07-31 15:30:19

By the way, I'm pretty sure this is unspecified behavior, but I could be wrong.

@greggo 2019-11-06 22:29:29

Fun fact: in C++, --x and ++x are lvalue. x-- and x++ are not. In C none of them are. Also, in C++, cond?a=3:b=2; means cond?(a=3):(b=2);, whereas in C it is not legal (it would mean (cond?(a=3):b)=2; -- which isn't legal since (a=3) isn't an lvalue).

@Sajad Bahmani 2009-11-18 12:52:03

This code first compares x and 0 and then decrements x. (Also said in the first answer: You're post-decrementing x and then comparing x and 0 with the > operator.) See the output of this code:

9 8 7 6 5 4 3 2 1 0

We now first compare and then decrement by seeing 0 in the output.

If we want to first decrement and then compare, use this code:

#include <stdio.h>
int main(void)
    int x = 10;

    while( --x> 0 ) // x goes to 0
        printf("%d ", x);
    return 0;

That output is:

9 8 7 6 5 4 3 2 1

@H-005 2020-07-31 06:02:01

--x> 0 Is that x in a spaceship going towards 0 (the moon)?

@Rajeev Das 2013-04-02 11:22:40

It's a combination of two operators. First -- is for decrementing the value, and > is for checking whether the value is greater than the right-hand operand.


int main()
    int x = 10;

    while (x-- > 0)
        printf("%d ",x);

    return 0;

The output will be:

9 8 7 6 5 4 3 2 1 0            

@Stone Mason 2010-01-17 00:46:01

My compiler will print out 9876543210 when I run this code.

#include <iostream>
int main()
    int x = 10;

    while( x --> 0 ) // x goes to 0
        std::cout << x;

As expected. The while( x-- > 0 ) actually means while( x > 0). The x-- post decrements x.

while( x > 0 ) 
    std::cout << x;

is a different way of writing the same thing.

It is nice that the original looks like "while x goes to 0" though.

@Tim Leaf 2010-05-05 15:30:19

The result is only undefined when you're incrementing/decrementing the same variable more than once in the same statement. It doesn't apply to this situation.

@Bernhard Barker 2015-05-22 12:28:30

while( x-- > 0 ) actually means while( x > 0) - I'm not sure what you were trying to say there, but the way you phrased it implies the -- has no meaning whatsoever, which is obviously very wrong.

@Mark Lakata 2020-02-24 16:41:38

To drive the point home from @Dukeling, this answer is not the same as the original post. In the original post, x will be -1 after it leaves the loop, while in this answer, x will be 0.

@Good Person 2009-12-31 13:48:19

This is exactly the same as

while (x--)
   printf("%d ", x);

for non-negative numbers

@Mateen Ulhaq 2011-12-04 21:32:19

Shouldn't this be for(--x++;--x;++x--)?

@Cole Johnson 2013-03-23 18:39:13

@DoctorT that's what unsigned is for

@WorldSEnder 2015-06-19 02:02:01

@MateenUlhaq, that is wrong according to the standard the expression --x++ has undefined behaviour according to §1.9.15

@Cacahuete Frito 2019-02-21 22:01:27

If it were using unsigned, it would have used %u

@NguyenDat 2010-04-09 00:04:09

One book I read (I don't remember correctly which book) stated: Compilers try to parse expressions to the biggest token by using the left right rule.

In this case, the expression:


Parses to biggest tokens:

token 1: x
token 2: --
token 3: >
token 4: 0
conclude: x-- > 0

The same rule applies to this expression:


After parse:

token 1: a
token 2: --
token 3: --
token 4: -
token 5: b
conclude: (a--)-- - b

I hope this helps to understand the complicated expression ^^

@Tim Leaf 2010-05-05 15:26:03

Your second explanation is not correct. The compiler will see a-----b and think (a--)-- - b, which does not compile because a-- does not return an lvalue.

@Roland Illig 2010-07-02 19:20:05

Additionally, x and -- are two separate tokens.

@v.oddou 2014-09-01 03:34:53

@DoctorT: it passes the lexer. only semantic pass is capable of emmiting that error. so his explanation is correct.

@Bernhard Barker 2015-05-22 12:33:43

As long as you think --> is an operator (which is what's implied by having the question that was asked), this answer isn't helpful at all - you'll think token 2 is -->, not just --. If you know that --> isn't an operator, you probably don't have a problem understanding the code in the question, so, unless you have a completely different question, I'm not really sure how this could be useful.

@doc 2015-07-08 11:20:12

@DoctorT example can be correct assuming that a has overloaded post-decrement operator, which returns lvalue.

@Buge 2016-01-08 01:41:16

It explains why it doesn't get parsed to a - -> b since -> is an operator itself.

@Hola Soy Edu Feliz Navidad 2018-08-29 14:02:25

Tried a-----b and the compiler says Expression is not assignable, even when using c++11.

@Pandrei 2014-02-10 17:29:22

C and C++ obey the "maximum munch" rule. The same way a---b is translated to (a--) - b, in your case x-->0 translates to (x--)>0.

What the rule says essentially is that going left to right, expressions are formed by taking the maximum of characters which will form an valid expression.

@david 2014-08-28 00:41:45

Which is what the OP assumed: that "((a)-->)" was the maximal munch. It turns out that the OP's original assumption was incorrect: "-->" is not a maximum valid operator.

@Roy Tinker 2015-07-11 01:04:15

Also known as greedy parsing, if I recall correctly.

@Marquis of Lorne 2016-09-11 02:21:50

@RoyTinker Greedy scanning. The parser has nothing to do with this.

@AndroidLearner 2012-08-18 07:34:12

Actually, x is post-decrementing and with that condition is being checked. It's not -->, it's (x--) > 0

Note: value of x is changed after the condition is checked, because it post-decrementing. Some similar cases can also occur, for example:

-->    x-->0
++>    x++>0
-->=   x-->=0
++>=   x++>=0

@Florian F 2014-09-01 09:46:25

Except that ++> can hardly be used in a while(). A "goes up to..." operator would be ++<, which doesn't look anywhere as nice. The operator --> is a happy coincidence.

@underscore_d 2016-11-12 17:57:29

@BenLeggiero That could 'work' in the sense of generating code that does something (while infuriating readers who don't like faux-clever code), but the semantics are different, as its use of predecrement means it will execute one fewer iteration. As a contrived example, it would never execute the loop body if x started at 1, but while ( (x--) > 0 ) would. {edit} Eric Lippert covered both in his C# 4 release notes:…

@Test 2009-10-29 14:45:22

Anyway, we have a "goes to" operator now. "-->" is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.

Furthermore, it is a little more efficient than "for (x = 10; x > 0; x --)" on some platforms.

@Ganesh Gopalasubramanian 2009-11-13 03:22:41

Goes to cant be true always especially when value of x is negative.

@Pete Kirkham 2010-06-21 08:57:44

The other version does not do the same thing - with for (size_t x=10; x-->0; ) the body of the loop is executed with 9,8,..,0 whereas the other version has 10,9,..,1. It's quite tricky to exit a loop down to zero with an unsigned variable otherwise.

@tslmy 2013-06-15 02:49:10

I think this is a little bit misleading... We don't have a literally "goes to" operator, since we need another ++> to do the incremental work.

@SamB 2013-12-06 06:57:56

@Josh: actually, overflow gives undefined behavior for int, so it could just as easily eat your dog as take x to zero if it starts out negative.

@Marc van Leeuwen 2014-08-30 20:08:39

This is a very important idiom to me for the reason given in the comnmet by @PeteKirkham, as I often need to do decreasing loops over unsigned quantities all the way to 0. (For comparison, the idiom of omitting tests for zero, such as writing while (n--) instead for unsigned n, buys you nothing and for me greatly hampers readability.) It also has the pleasant property that you specify one more than the initial index, which is usually what you want (e.g., for a loop over an array you specify its size). I also like --> without space, as this makes the idiom easy to recognise.

@Marc van Leeuwen 2014-08-30 20:16:12

... Actually, I somewhat regret that writing while(0<--n) does not do the same thing as writing while(n-->0), and the former is usually not what you want. On the other hand, at least in C++, you can make it descend twice as fast with while(0<----n).

@Horse SMith 2014-11-21 02:12:47

x=10; while(x --> 0) is not the same as for(x=10; x>0; x--)... it would on the other hand be the same as for(x=10-1; x=>0; x--) .

@Narfanar 2015-05-26 07:57:21

Well, also while(0 <=-- x). But this's getting silly(er) :p

@Artelius 2020-08-21 01:36:47

With any level of compiler optimisation, there is no difference in efficiency. The assembly output is identical.

@Escualo 2010-05-18 20:33:28

Utterly geek, but I will be using this:

#define as ;while

int main(int argc, char* argv[])
    int n = atoi(argv[1]);
    do printf("n is %d\n", n) as ( n --> 0);
    return 0;

@mouviciel 2012-11-14 10:00:02

@SAFX - It would be perfectly hieroglyphics with egyptian brackets

@Marquis of Lorne 2016-09-11 02:20:23

This doesn't compile. C is not Pascal, where the interior of do ... while is a statement list. In C it is a block, so it must be do { ... } while.

@Escualo 2016-10-18 17:28:10

@EJP it does compile. The syntax is do statement while ( expression ) ;. Having said that, I hope it is understood I meant the example as a joke.

@sam 2010-04-06 10:45:37

-- is the decrement operator and > is the greater-than operator.

The two operators are applied as a single one like -->.

@underscore_d 2016-11-12 17:56:09

They're applied as the 2 separate operators they are. They're only written misleadingly to look like "a single one".

@Mr. X 2009-12-28 16:32:54

There is a space missing between -- and >. x is post decremented, that is, decremented after checking the condition x>0 ?.

@user529758 2012-08-02 19:16:31

The space is not missing - C(++) ignores whitespace.

@Jens 2013-04-25 21:16:44

@H2CO3 This isn't true in general. There are places where white space must be used to separate tokens, e.g. in #define foo() versus #define foo ().

@Kevin P. Rice 2013-12-04 20:35:14

@Jens How about: "The space is not missing - C(++) ignores unnecessary white space."?

@Grumdrig 2009-10-29 07:00:20

while( x-- > 0 )

is how that's parsed.

@Matt Joiner 2009-11-18 12:47:41

The usage of --> has historical relevance. Decrementing was (and still is in some cases), faster than incrementing on the x86 architecture. Using --> suggests that x is going to 0, and appeals to those with mathematical backgrounds.

@burito 2009-12-30 05:16:46

Not exactly true. Decrementing and Incrementing take the same amount of time, the benefit of this is that comparison to zero is very fast compared to comparison versus a variable. This is true for many architectures, not just x86. Anything with a JZ instruction (jump if zero). Poking around you can find many "for" loops that are written backwards to save cycles on the compare. This is particularly fast on x86 as the act of decrementing the variable set the zero flag appropriately, so you could then branch without having to explicitly compare the variable.

@Joey Adams 2010-04-12 15:07:58

Well, decrementing toward zero means you only have to compare against 0 per loop iteration, while iterating toward n means comparing with n each iteration. The former tends to be easier (and on some architectures, is automatically tested after every data register operation).

@Duncan 2014-01-11 09:05:12

@burrito Although I don't disagree, loops conditioned on non-zero values generally get predicted near perfectly.

@Alice 2014-03-25 04:26:53

@Konerak Going from an O(N) operation to an O(1) one is almost always preferable.

@Rob11311 2014-05-29 13:04:46

The C increment/decrement operators gave access to PDP11 instructions. On that arch *p++ was faster than *++p, and *--p than *p--. I can't remember if p++, p-- & ++p, --p, differed in cycle times but there were micro-optimisations available to those who coded carefully. The reason, was the arch was tuned to support the very common stack operations, push & pop.

@lego 2015-02-18 11:14:01

Increment and decrement are equally fast, probably on all platforms (definitely on x86). The difference is in testing the loop end condition. To see if the counter has reached zero is practically free - when you decrement a value, a zero flag is set in processor and to detect the end condition you just need to check that flag whereas when you increment a comparison operation is required before end condition can be detected.

@Lambda Fairy 2015-02-20 03:53:56

Of course, all this is moot these days, since modern compilers can vectorize and reverse loops automatically.

@Bernhard Barker 2015-05-22 12:55:22

This would be better as a footnote in another answer or a comment - it clearly doesn't explain what --> means, which is what was asked.

@Philip Oakley 2015-06-23 16:14:55

IIRC the PDP11 *p++ was the basis for the FORTH implementation and part of it's great speed (compiled code being 'faster' than regular assembler, and it didn't need to access or use a call instruction ;-)

@Mark K Cowan 2015-07-08 11:26:58

In x86 ASM, the LOOP <address> decreases the ECX register, then jumps to <address> unless the decrementing of ECX resulted in zero. Decrementing the loop counter towards zero allows the compiler to generate a single LOOP instruction, whereas incrementing or counting to other values requires separate INC/DEC/ADD/SUB, compare, and conditional jump instructions. Modern compilers can often convert other loops to a counter --> 0 loop if the value of counter isn't used in the loop.

@Mark K Cowan 2015-07-08 11:32:17

Continuing my previous comment: MOV ECX, value, @start:, <code>, LOOP @start is an x86 ASM equivalent for counter = value - 1; while (counter --> 0) { <code>; }. Note that it will barf if value is initially zero, so an extra check is needed pre-loop.

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] The Definitive C++ Book Guide and List

  • 2008-12-23 05:23:56
  • grepsedawk
  • 2453202 View
  • 4241 Score
  • 1 Answer
  • Tags:   c++ c++-faq

15 Answered Questions

[SOLVED] What is the effect of extern "C" in C++?

20 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

41 Answered Questions

36 Answered Questions

[SOLVED] What is the !! (not not) operator in JavaScript?

  • 2009-04-24 08:13:58
  • Hexagon Theory
  • 600795 View
  • 3240 Score
  • 36 Answer
  • Tags:   javascript operators

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

4 Answered Questions

[SOLVED] What does the ??!??! operator do in C?

  • 2011-10-19 16:56:59
  • Peter Olson
  • 264481 View
  • 2026 Score
  • 4 Answer
  • Tags:   c operators trigraphs

11 Answered Questions

7 Answered Questions

Sponsored Content