Search code examples
cnegative-numberunsigned-integer

Prevent user passing negative numbers to a function accepting unsigned int


So here's the code:

int create_mask(unsigned b, unsigned e)
{
  unsigned int mask=1;

  if(b<e || b<0 || e<0)
  {
    printf("Wrong values, starting bit can't be smaller than ending.\n");
    printf("Both got to be >= 0.\n");
    exit(EXIT_FAILURE);
  }
  while(b>0)
  {
    printf("%u\n", b);
    mask<<=1;
    if(b>e)
      mask|=1;
    b--;
  }

  return ~mask; /* negates mask for later purpose that is clearing corresponding bits */
}

Function creates mask for some bit operations, but should take two unsigned ints b and e, both non-negative. Question is how to prevent user input of negative numbers? When function is called with (-1,0) it start the loop, and shoult exit with error.


Solution

  • You could just input a string, check if it contains a '-' character, and yield an error if it does. Else you convert it to an unsigned integer and proceed on. (Reading as a string then converting with strtoul() is preferred over using scanf() anyway, especially while you aren't aware of all of the quirks of scanf().)

    char buf[LINE_MAX];
    fgets(buf, sizeof buf, stdin);
    
    if (strchr(buf, '-') != NULL) {
        fprintf(stderr, "input must be non-negative!\n");
        exit(-1);
    }
    
    unsigned int n = strtoul(buf, NULL, 0);