Simple logic question

What does the logical expression

 
!vec.size() == 0

mean? I tried googling it, but didn't really find any answer.
It states whether
!( vec.size() > 0 ) is false
or
vec.size() > 0 is true

i.e. it states (in an extremely obscure manner) whether vec has any elements in.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
using namespace std;

int main()
{
   vector<int> vec = { 1, 2, 3 };
   cout << boolalpha << ( !vec.size() == 0 ) << '\n';         // true

   vec.clear();
   cout << boolalpha << ( !vec.size() == 0 ) << '\n';         // false
}


For numerical values, anything non-zero can be cast, where required, to a boolean of true. Anything zero would be cast to false.

In the opposite direction, true would be cast to 1 and false would be cast to 0.


For operator precedence, see https://en.cppreference.com/w/cpp/language/operator_precedence
In this instance the ! would be applied before the ==


I think I would use either
if ( !vec.empty() )
or
if ( vec.size() )
instead
Last edited on
Pretty sure "!" has higher precedence than "==", so that !vec.size() == 0 is not the same thing as !(vec.size() == 0) if that is so, what's going to happen here is that the result of the call to size(), probably an unsigned integral type, will be converted to a boolean, either true or false, that answer will be logically inverted, promoted to an int, and compared to 0, for equality. Below, res is the value of the expression. Imagine:

1
2
3
4
5
size_t len = vec.size();
bool b = (bool) len;
bool nb = !b;
int ilen = (int) nb;
bool res = ilen == 0;
My opinion would be to avoid constructs like this, that convert an integer to a boolean to then compare it with an integer. I think it looks confusing and it's hard to tell it apart from a typo.

I think I would use either
if ( !vec.empty() )
or
if ( vec.size() )
instead
This makes much more sense.
(Personally I'd even be more explicit in that last one, and do if (vec.size() > 0))
Last edited on
I agree, simplify and clarify. first, the original expression does 2 things (a not and a compare) so it is wasteful, and second, it does 2 things when 1 is all that is required, making it convoluted to read and unclear as to intent.

I would use Ganado's advice.
Topic archived. No new replies allowed.