简体   繁体   English

为什么GCC4警告以及如何避免

[英]Why gcc4 warn and how to avoid it

I have a function declared as: 我有一个函数声明为:

void    event_add_card (EventAddr addr, EventType type, unsigned char card);

and union 和联合

typedef union EventData
{
    float           money;      /**< money info */
    unsigned char   card;       /**< new card */
}
EventData;

When i compile following code: 当我编译以下代码时:

EventData data = {};

event_add_card (0,0, data.card);

with enabled warning -Wconversion I receive following warning: 启用警告-Wconversion我收到以下警告:

player-stud.c|71| warning: passing argument 3 of 'event_add_card' with different width due to prototype

Why gcc4 unsuccessful and how to fix It??? 为什么gcc4不成功以及如何解决???

In versions of gcc prior to 4.3, -Wconversion produces a warning when the behaviour may be different depending on whether or not a prototype is in scope. 在4.3之前的gcc版本中,如果行为可能取决于原型是否在范围内,则-Wconversion会产生警告。 In the example you give, argument 3 ( data.card ) is of unsigned char ; 在您给出的示例中,参数3( data.card )是unsigned char if the prototype for event_add_card() is in scope, it will be passed as an unsigned char , but if the prototype is not in scope it will be passed as an int due to C's integer promotion rules - hence the warning. 如果event_add_card()的原型在范围内,则将以unsigned char形式传递;但是,如果原型不在范围内,则由于C的整数提升规则而将以int形式传递-因此发出警告。

This isn't very useful, except during the process of converting old K&R-style code to use prototypes. 除了将旧的K&R风格的代码转换为使用原型的过程之外,这不是很有用。 As such, if you're using an older version of gcc, it's not a generally useful option to enable. 因此,如果您使用的是旧版的gcc,启用它通常不是有用的选项。

From gcc 4.3 onwards, the behaviour has changed: it now warns about any implicit conversion which might change a value (say, between signed and unsigned integers, or integers and floats). 从gcc 4.3开始,行为已更改:现在警告任何可能更改值的隐式转换(例如,在有符号和无符号整数之间,或整数和浮点数之间)。 This is considerably more useful. 这是非常有用的。 (The previous functionality hasn't gone, though: it's still available, but renamed as -Wtraditional-conversion .) (不过,以前的功能还没有消失:它仍然可用,但已重命名为-Wtraditional-conversion 。)

(More details at http://gcc.gnu.org/wiki/NewWconversion .) (有关更多详细信息,请参见http://gcc.gnu.org/wiki/NewWconversion 。)

The problem is that you're using -Wconversion 问题是您正在使用-Wconversion

There is nothing wrong with your code, and nothing you can do to make -Wconversion not produce that warning. 您的代码没有错,也没有任何办法使-Wconversion不产生该警告。

Example: 例:

void someFunction(unsigned char foo);
...
unsigned char bar = 'f';
someFunction(bar);

This will produce the same error if you compile and use -Wconversion 如果您编译并使用-Wconversion,将产生相同的错误

-Wconversion is meant to identify issues when converting between K&R and ISO C, which you aren't doing. -Wconversion旨在确定在K&R和ISO C之间进行转换时没有做的问题。

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

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