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);
    }
}

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?

21 comments

@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)
    {
        a--;
        // Code
    }
    a--;
}

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'.

@Vladislav Toncharov 2019-05-12 10:59:49

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

@JL2210 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.

@Steven Devijver 2013-02-12 08:07:27

In Java it also compiles :)

@aring 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.

@v.oddou 2014-09-01 03:38:10

@sellibitze and knittl, not to even mention the fact that post 3 address code generation optimization is still possible and store/loads may be moved around in any order as long as it doesnt change the observable behavior, by one thread. And this is true at compiler level, and CPU level as well (OOO). So while your correction is true at the virtual C++ machine level, its false in practice.

@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).

@Rik Schaaf 2016-05-23 04:23:54

int x = 0; int y = 10; do{ printf("%d", -x); }while(-y <-- x); Less good since you need to negate the value of x and y, but it does result into an increasing range operator

@skyking 2016-06-27 11:08:20

@knittl I don't think there support for your claim in the standard. The standard only says that x-- means to decrease the value of x while the value of the expression is the original value of x.

@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.

@android developer 2016-08-14 16:41:58

For a moment I thought it was about "->" . What is the name of this operator?

@Thomas 2016-08-16 11:02:34

@androiddeveloper The one in the question has no standard name, the one in your comment is called the dereference (or indirection) operator.

@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.

@Vladislav Toncharov 2018-04-08 15:46:29

It's actually a useful feature: an easier way to create a countdown loop (shorter than for)

@user9791370 2019-07-17 15:01:15

I think x -->0 is kind of cool looking actually

@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
}

@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.

@PerpetualJ 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…)

@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...

@mafu 2012-03-07 10:48:26

Sorry, I don't get this one. How does this work?

@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 02:52:27

@Arnav Borborah 2016-09-10 10:28:42

@unsynchronized but where is the 'words'

@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."

@Will Croxford 2018-07-30 11:26:33

+1 for (Monty) Python reference, ...and now for something completely different... a smooth operator with a sliding nose (the sliding nose is the rough operator maybe?)

@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".

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

It's

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

     while( x-- > 0 ){ // x goes to 0

       printf("%d ", x);
     }

     return 0;
}

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

@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. coliru.stacked-crooked.com/a/f5fdc710da0398c9

@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? --> coliru.stacked-crooked.com/a/5aa89a65e3a86c98

@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!

@MD XF 2017-02-21 16:15:58

@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.

@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

@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.

#include<stdio.h>

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 ) 
{
    x--;
    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.

@Dukeling 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.

@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:

x-->0

Parses to biggest tokens:

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

The same rule applies to this expression:

a-----b

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.

@RJFalconer 2014-03-13 11:09:26

This is known as Maximal munch.

@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.

@Dukeling 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. coliru.stacked-crooked.com/a/e1effc351ae79e9f

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

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

@BJovke 2016-11-26 10:37:28

Actually (x-)-> would be a syntax error.

@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.

@user207421 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.

@Ben Leggiero 2015-06-15 14:00:33

Could while (0 <-- x) also work, then?

@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: blogs.msdn.microsoft.com/ericlippert/2010/04/01/…

@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

@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

@user207421 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.

@Dukeling 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

5 Answered Questions

24 Answered Questions

[SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

4 Answered Questions

[SOLVED] How do I achieve the theoretical maximum of 4 FLOPs per cycle?

24 Answered Questions

[SOLVED] What does the C++ standard state the size of int, long type to be?

  • 2009-02-26 07:59:23
  • Jérôme
  • 1186800 View
  • 665 Score
  • 24 Answer
  • Tags:   c++ c++-faq

4 Answered Questions

[SOLVED] Is returning void valid code?

  • 2010-08-01 17:49:40
  • Karel Petranek
  • 7819 View
  • 55 Score
  • 4 Answer
  • Tags:   c++ c

20 Answered Questions

5 Answered Questions

[SOLVED] Why is (void) 0 a no operation in C and C++?

8 Answered Questions

[SOLVED] How fast is D compared to C++?

3 Answered Questions

4 Answered Questions

[SOLVED] Throw and ternary operator in C++

Sponsored Content