Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop should not execute

In this code

std::vector<int> vec;
    
    for (int i = 0; i < vec.size() - 1; i++) {

        std::cout << "Print" << std::endl;
    }

Though vec has no input members so the for loop should not execute at all since "i" will be more than the the condition for execution which is vec.size() – 1

But still the loop is executing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

vec.size() returns an unsigned type. Now vec.size() is 0, but vec.size() - 1 will cause an wrap around, so that’s why you see

std::cout << "Print" << std::endl;

executed

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading