Search code examples
cgccinthexundefined

Trying to store invalid hexadecimal number in int variable


I have a very basic doubt. I am trying to store any invalid hex number in an int variable. By invalid number i mean a number that is using alphabets that are not in A-F range. For example see this program:

#include<stdio.h>
int main()
{
    int a;
    scanf("%X",&a);
    printf("%d",a);
    return 0;
}

When console asks for input, I entered G. It gave the output as 63. Is it just undefined behaviour or there is some logic behind this output. For most of such inputs the output is coming out as 63. Currently working on GCC.


Solution

  •  scanf("%X",&a);
    

    %X will seek for hexadecimal input only. If you input G the directive will fail, and no assignment to a will happen. In this case scanf() returns 0, which specifies the number of items successfully consumed.

    You should check if all items were successfully consumed by checking the return value of scanf():

    if(scanf("%X",&a) != 1) {
        fprintf(stderr, "Error occurred at scanning hexadecimal input!");
    }
    

    "When console asks for input, I entered G. It gave the output as 63. Is it just undefined behaviour or is there some logic behind this output?"

    Since a is uninitialized:

    int a;
    

    and there was no consumption successfully at the scanf() call which would have assigned a reasonable value to a, a still contains a garbage value as it is an object of the storage duration automatic by default.

    To print this garbage value value invokes indeed undefined behavior.