Which input number will execute the else block with the above condition?
Most likely your system uses 32 bit unsigned int with maximum value 4294967295.
If so, there is no input that can trigger the else
block.
As commented by many, the simple solution is to use a variable with more bits (if possible). But as pointed out by @Brendan it just give you other problems.
A more robust solution is to write your own function to parse the input instead of using scanf
Such a function could be something like this:
#include <stdio.h>
#include <limits.h>
// Returns 1 if the string can by converted to unsigned int without overflow
// else return 0
int string2unsigned(const char* s, unsigned int* u)
{
unsigned int t = 0;
if (*s > '9' || *s < '0') return 0; // Check for unexpected char
while(*s)
{
if (*s == '\n') break; // Stop if '\n' is found
if (*s > '9' || *s < '0') return 0; // Check for unexpected char
if (t > UINT_MAX/10) return 0; // Check for overflow
t = 10 * t;
if (t > UINT_MAX - (*s - '0')) return 0; // Check for overflow
t = t + (*s - '0');
s++;
}
*u = t;
return 1;
}
int main(void) {
unsigned int u;
char s[100];
if (!fgets(s, 100, stdin)) // Use fgets to read a line
{
printf("Failed to read input\n");
}
else
{
if (string2unsigned(s, &u))
{
printf("OK %u\n", u);
}
else
{
printf("Illegal %s", s);
}
}
return 0;
}
Example:
input: 4294967295
output: OK 4294967295
input: 4294967296
output: Illegal 4294967296
(Thanks to @chux for suggesting a better alternative to my original code)