简体   繁体   中英

warning on type casting in C

In C, strlen returns a unsigned long .

I'm using an int variable to store it. Why is there no warning?

Could someone give an explanation when it will be a warning and when it will not?

C does not require any diagnostic when you assign a value of an arithmetic type T1 to an object of another arithmetic type T2 .

A lot of implementations issue an informative diagnostic when you assign a literal value that does not fit in an object and in other cases but again it is not required by C.

C is not strict on type safety so a conforming implementation may choose not to issue a warning.

Perhaps you can try some option with verbose warning, -Wall or similar for your compiler if you want the warning to avoid any such type-safety issue.

This is one of the pitfall of C , as if the value is larger than what signed int can represent, behavior is implementaion-defined.

EDIT

Quoting from 6.3.1.3 Signed and unsigned integers

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM