Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

c - Scanning a number having more data than predefined value

#include<stdio.h>
main()
{

        unsigned int num;
        printf("enter the number:
");
        scanf("%u",&num);//4294967299 if i'm scanning more than 4G its not scanning
        printf("after scanning num=%u
",num);// 4294967295 why its giving same 4G

        /*      unsigned char ch;
                printf("enter the character:
");
                scanf("%d",&ch);// if i/p=257 so its follow circulation
                printf("after scanning ch=%d
",ch);// 1 its okk why not in int ..
         */
}

Why is circulation not following while scanning input via scanf(), why is it following in case of char?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The C11 standard draft n1570 7.21.6.2 says the following

paragraph 10

[...] the input item [...] is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *, 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.

Now, the word "conversion" here is used for string => result data type conversion, it cannot be understood to mean integer conversions. As the string "4294967299" converted to a decimal integer is not representable in an object of type unsigned int that is 32-bit wide, the reading of the standard says that the behaviour is undefined, i.e.

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

Thus, the answer to your question is that the C standard doesn't state the behaviour in this case, and the behaviour you see is the one exhibited by your compiler and C library implementation, and is not portable; on other platforms the possible behaviours might include:

ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...