bex91
bex91

Reputation: 123

Omitted for loop values

It's my first post here and my first time with C++. I'm looking at some code I got from the Internet but I have a question about it.

It has a for loop, like this:

for(cin >> t;t--;)

I understand what it's doing, but I can't understand what the condition is.

According to this format, for ( init; condition; increment ), t-- is the condition, but it doesn't make much sense. I think that t-- is the increment, but why is it the second parameter?

Shouldn't it be something like: for (cin >> t; ;t--); ?

Upvotes: 1

Views: 311

Answers (2)

congusbongus
congusbongus

Reputation: 14622

for ( init; condition; increment ) is just the recommended way to use for loops. The real way for loops work is:

for(
    <runs once before loop>;
    <check before every iteration, loop if true/non-zero>;
    <run after every iteration>)

Upvotes: 0

Jack
Jack

Reputation: 133587

The -- operator is an "decrement and return" operator. Since it is used as postdecrement, it returns t and then decrement the value.

In C++ everything that is different from 0 is true and viceversa so basically it's equivalent to

t == 0

Of course things would be different in case of --t, since it would decrement the value before and then return it (it would end the loop one iteration earlier).

Upvotes: 2

Related Questions