Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ for loop structure

Tags:

c++

Hope its not a lame question but I have to ask this :)

When I program in C++ and use for loops the parameters I give are i.e.

for(int i = 0; i< something; i++)

Which is correct way forward but..this gives me compile warnings such as this:

1>c:\main.cpp(185): warning C4018: '<' : signed/unsigned mismatch 

Now going through books and reading online most for loops examples are of this structure.

I was always ignoring warnings as my programs always worked and did what they suppose to do, until I got interested with this warnings and did a small research....by copying this Waring and Google it to find that it is better if I use this structure to avoid the warning:

for(vector<int>::size_type i= 0; i < something; i++ )

Now my question here is why......if the initial structure works and is described and documented in many books and online resources.

Also what is the benefit or is there any significant difference in the techniques.....?

Why would I use this

for(vector<int>::size_type i= 0; i < something; i++ )

apart from getting rid of the warnings.....?

like image 370
Tomazi Avatar asked Dec 09 '22 16:12

Tomazi


1 Answers

Don't ignore the warnings. They're trying to tell you something.

I suspect something is unsigned.

If you have

unsigned int something = 0;
something--;  // Now something is a really large positive integer, not -1

If you ignore the warnings, and you don't have your compiler set to treat warnings as errors, then this will compile fine, but you won't get what you expect.

You're probably seeing that vector<int>::size_type is an unsigned int if the warning goes away.

like image 53
John Avatar answered Dec 11 '22 06:12

John