Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have got weird result when i executed this for-loop with auto keyword. could someone explain why i got weird result in this for-loop?

C++
#include <iostream>

int main()
{
	for (auto i = 0u; i < 3u; ++i) // Okay
	{
		std::cout << i << ' ';
	}

	for (auto i = 2u; i >= 0u; --i) // ?????? Awful
	{
		std::cout << i << ' ';
	}
}
Posted

1 solution

You are declaring your values as unsigned so when i goes from 0 to -1 it is treated as the unsigned value 0xFFFFFFFF, and the loop goes on forever. If you change the second loop statement to
C++
for (auto i = 2u; i > 0u; --i)
// or
for (auto i = 2u; i != 0xFFFFFFFFu; --i)
// or better 
for (auto i = 2; i >= 0; --i) // use signed numbers

it will work. It is better to use signed numbers as much as possible to avoid issues such as this.
 
Share this answer
 
Comments
Andreas Gieriet 3-Jan-16 9:32am    
My 5!
Cheers
Andi
Richard MacCutchan 3-Jan-16 9:43am    
My first 5 of 2016, thank you.
Sergey Alexandrovich Kryukov 3-Jan-16 12:39pm    
5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900