简体   繁体   English

在C中进行类型转换警告

[英]warning on type casting in C

In C, strlen returns a unsigned long . 在C中, strlen返回一个unsigned long

I'm using an int variable to store it. 我正在使用一个int变量来存储它。 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 . 将算术类型T1的值分配给另一个算术类型T2的对象时,C不需要任何诊断。

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并不需要它),很多实现都会发出信息诊断。

C is not strict on type safety so a conforming implementation may choose not to issue a warning. C对类型安全性不严格,因此符合要求的实现可以选择不发出警告。

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. 如果希望警告避免任何此类类型安全问题,则可以为编译器尝试一些选项,包括详细警告, -Wall或类似选项。

This is one of the pitfall of C , as if the value is larger than what signed int can represent, behavior is implementaion-defined. 这是C的陷阱之一,就好像值大于signed int可以表示的值一样,行为是实现定义的。

EDIT 编辑

Quoting from 6.3.1.3 Signed and unsigned integers 引用6.3.1.3有符号和无符号整数

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. 将具有整数类型的值转换为_Bool以外的其他整数类型时,如果该值可以用新类型表示,则该值不变。
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. 结果是实现定义的,还是引发实现定义的信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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