user3495562
user3495562

Reputation: 335

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?

Upvotes: 1

Views: 96

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

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.

Upvotes: 3

ouah
ouah

Reputation: 145829

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.

Upvotes: 5

Related Questions