1

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 condition for execution which is vec.size() - 1.

But still the loop is executing.

Evg
  • 25,259
  • 5
  • 41
  • 83
Summit
  • 2,112
  • 2
  • 12
  • 36
  • Replace `vec.size() - 1` with `vec.size() ` – Jason Jan 08 '22 at 04:21
  • 3
    Always compile C++ with warnings on (`-Wall` on gcc). It'll tell you about things like this. – Silvio Mayolo Jan 08 '22 at 04:22
  • 3
    ```vec.size()``` returns an unsigned value 0, which will underflow and rotate to ```std::limits::max()``` when you subtract ```1``` from it. I wonder if you don't get a warning message while compiling that code segment. – Paulo1205 Jan 08 '22 at 04:23
  • 2
    https://www.geeksforgeeks.org/vectorempty-vectorsize-c-stl/ so suggestion is to typeast `(int)vector.size() - 1`. By the way, shouldn't you be doing `i < vec.size()`? – gp. Jan 08 '22 at 04:26
  • @SilvioMayolo It will warn, but at least for GCC and Clang only about the signed/unsigned comparison. Naively replacing `int` with `unsigned` then produces no warning: https://godbolt.org/z/jW6ooYaf5 – user17732522 Jan 08 '22 at 05:15
  • @gp. This is a bad way to do it. On 64-bit platforms `vector.size()` could not fit into `int`. – Evg Jan 08 '22 at 06:38

1 Answers1

4

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