Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does x = 12345678901234567890 return "x is less than y" when y = 1?

#include <stdio.h>

int main(void){

int x;
int y;
printf("What's x? ");
scanf("%d",&x);

printf("What's y? ");
scanf("%d",&y);

if (x < y)
{
    printf("x is less than y\n");
}
else if (x > y)
{
    printf("x is greater than y\n");
}
else
{
    printf("x and y are equal");
}

return 0;
}

Input:
12345678901234567890
1

Output:
x is less than y

expecting program to return "x is greater than y" when x = 12345678901234567890 and y = 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The %d conversion specifier requires the corresponding scanf argument to be a pointer to int. The decimal digit sequence 12345678901234567890 corresponds to a number that is very likely to be outside the range that your int (probably a 32-bit type) can represent. Supposing that it is indeed out of range, the behavior of your program is undefined when processing the input specified. That means anything can happen, as far as the language spec is concerned.

C23 7.23.6.2/10:

the result of the conversion is placed in the object pointed to by the
first argument following the format argument that has not already
received a conversion result. If this object does not have an
appropriate type, or if the result of the conversion cannot be
represented in the object, the behavior is undefined.

(Emphasis added.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading