-0.69's blog

By -0.69, history, 20 months ago, In English

I recently faced an issue due the fact that I didn't placed an 'int' before the looping for a vector that was constructed. It works without (int) sometimes but this time It gave warnings. Can someone explain this behavior. Thankyou.

  • Vote: I like it
  • +8
  • Vote: I do not like it

»
20 months ago, # |
Rev. 2   Vote: I like it +43 Vote: I do not like it

The function size()'s return type is size_t which is an unsigned int.
So, for example, if you do v.size() - 1 for an empty vector(size = 0) it will not result in -1 but some large number.
Maybe you did something similar to this.

»
20 months ago, # |
  Vote: I like it +8 Vote: I do not like it

This doesn't answer your question, but it's pretty common to define a macro #define sz(c) int((c).size()) to avoid underflow issues without having to put int() all over the place. Alternatively, in C++20 you can use ssize(c) (see cppreference), which returns the size in a signed type.