-6

have this small sample of code:

size_t value;

value = (size_t) strtol(argv[1], NULL, 10);
if (value <= 0) {
     fprintf(stderr, "Value cant be 0 or a negative value\n");
     return 1;
}

When I run ./prog -1, it doesn't fail with Value cant be 0 or a negative value which doesn't make sense to me. Am I missing something?

If I run ./prog 0, it does fail, but not if the argument is with -.

robertalks
  • 9
  • 1
  • 3
  • 7
    `size_t` is an unsigned type, so `value` cannot be negative. – mch Apr 12 '16 at 08:54
  • Here some more details http://www.thecodingforums.com/threads/return-1-using-size_t.868206/ – kakurala Apr 12 '16 at 08:58
  • 2
    Make sure you compile with warnings enabled, e.g. `gcc -Wall ...`, then you get a warning for this mistake: `warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]` – Paul R Apr 12 '16 at 09:00
  • 1
    `size_t` is an unsigned data type defined by several C/C++ standards. This type is used to represent the size of an object. int - What is size_t in C? - http://stackoverflow.com/questions/2550774/what-is-size-t-in-c – Hasan Shahriar Apr 12 '16 at 09:01

1 Answers1

3

Type size_t is equivalent to unsigned integer (int or long). When you cast to size_t, it will always be positive (compiler should warn you about unsafe casting).

More about size_t: http://en.cppreference.com/w/cpp/types/size_t

burzan
  • 103
  • 4