newID
newID

Reputation: 141

Why does (0 > v.size()-1) evaluate to false for an empty vector?

I am using vector to do something and find the following condition is evaluated as false, which I could not understand.

The code is as follows:

#include "stdio.h"
#include <vector>

using namespace std;

int main()
{
   // an empty vector
   vector<int> v;

   // print 0
   printf ("size of the vector is %d \n", v.size());

   // the condition is false, why?
   if (0 > v.size()-1) {
       printf ("it should occur \n");
   }
}

Upvotes: 3

Views: 337

Answers (4)

Luchian Grigore
Luchian Grigore

Reputation: 258618

This is what happens when you mix signed and unsigned. v.size() returns a size_type which is an unsigned integer type (most likely the same as std::size_t, which often is a typedef for unsigned long (long)) , so your v.size()-1 wraps around, since it can never be a negative number.

If you enable warnings, the compiler would tell you that you're mixing signed and unsigned. For GCC, -Wall enables the relevant warning (which is -Wsign-compare)

Upvotes: 10

awesoon
awesoon

Reputation: 33691

Because std::vector::size returns value of std::vector::size_type type, which is unsigned.

warning: comparison of 0 > unsigned expression is always false [-Wtautological-compare]
   if (0 > v.size()-1) {
       ~ ^ ~~~~~~~~~~

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122473

Because v.size() returns a value of an unsigned type, which means when v.size() is 0, v.size()-1 is a very large positive number.

Upvotes: 3

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153975

The return type of v.size() is an unsigned type: std::vector<int>::size_type which is equivalent to std::size_t. Unsigned integers wrap around as they don't have a concept of negative values.

Upvotes: 2

Related Questions