dimanche 30 décembre 2018

Why does this stl function call result in an incorrect boolean evaluation?

I was humbly coding away when I ran into a strange situation involving checking the size of a vector. An isolated version of the issue is listed below:

#include <iostream>
#include <string>
#include <vector>

int main() {

  std::vector<std::string> cw = {"org","app","tag"};

  int j = -1;

  int len = cw.size();

  bool a = j>=cw.size();
  bool b = j>=len;


  std::cout<<"cw.size(): "<<cw.size()<<std::endl;
  std::cout<<"len: "<<len<<std::endl;

  std::cout<<a<<std::endl;
  std::cout<<b<<std::endl;

  return 0;
}

Compiling with both g++ and clang++ (with the -std=c++11 flag) and running results in the following output:

cw.size(): 3
len: 3
1
0

why does j >= cw.size() evaluate to true? A little experimenting that any negative value for j results in this weird discrepancy.

Aucun commentaire:

Enregistrer un commentaire