Ryan
Ryan

Reputation: 14659

How to validate that an argument is a positive number?

Although, I do define the function prototype as having a size_t type which is an unsigned type. I found that I can still pass negative numbers into the function, but the output will be a large signed decimal. The reason I ask this is because I want to validate an array index having known the array capacity.

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

void print(size_t i)
{
    printf("%zu\n", i);
}

int main()
{
    print(-1);

    return 0;
}

The output: 18446744073709551615

Is it possible to validate that the size_t i variable is greater than 0? If so how can I do this? gcc doesn't like me checking for i >= 0 because it says that i can never be less than zero.

Edit:

For further explanation. Imagine that you have to validate than an arbitrary decimal is passed to a function to get an element at index i. I want to make sure that index passed in is within a boundary. That boundary is: [0, N)

Upvotes: 2

Views: 403

Answers (2)

user3458
user3458

Reputation:

You're actually asking for a "reasonable" number check rather that negative number check (18446744073709551615 is indeed positive).

I could recommend comparing the size to some arbitrary limit such as 4 terabytes (4,398,046,511,104) (if it is indeed memory size).

If you indeed want to check for negative numbers, in gcc you can cast to ssize_t and then compare to 0.

Upvotes: 0

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215597

C's type promotion system, combined with the fact that the type of the argument is size_t, an unsigned type, precludes there from being any way to detect the incorrect usage from inside the function. However you can detect it from outside via a macro:

#define print(x) do { if ((x)<0) { /* error */ } else print(x); } while(0)

or similar.

Upvotes: 6

Related Questions