gcc将int *转换为枚举*错误 [英] gcc convert int * to enum * error
问题描述
#include <stdio.h>
typedef enum{
red=1,blue,green
}color;
void set_color(color *c)
{
*c = blue;
}
int main()
{
//int a = 3;
//set_color(&a);//why this error?
//set_color((color *)(&a));//It is right
color c = red;
set_color(&c); // this is right;
return 0;
}
i使用gcc -S用set_color((color *)(& a)查看汇编语言)和set_color相同( & c),但为什么gcc不自动执行转换?
i use gcc -S to view the assemble language with set_color((color *)(&a)) and it is the same with set_color(&c),but why gcc does not do the convertion automatically?
推荐答案
因为你定义了一个类型。因此隐式铸造不起作用。请参阅: http://en.cppreference.com/w/cpp/language/implicit_cast [ ^ ]
Because you defined a type. Thus implicit type casting won''t work. See: http://en.cppreference.com/w/cpp/language/implicit_cast[^]
因为它试图阻止你犯错误,而你却没有意识到这一点。
当你写作
Because it is trying to prevent you making a mistake, and you not realizing it.
When you write
set_color((color *)(&a));
你明确地转换它 - 告诉编译器这是我想要发送的值,我知道我在做什么所以它让它通过。
写的时候
You are explicitly converting it - telling the compiler "this is the value I wanted to send, I know what I am doing" so it lets it through.
When you write
set_color(&a);
这可能是一个错误 - 你可能没有意识到a根本就不是一种颜色。因此它会引发错误,因此您可以在问题成为运行时问题之前解决问题并导致奇怪的错误。
It could be a mistake - you might not have realised that "a" was not a color at all. So it raises an error so you can fix the problem before it becomes a run time problem and causes an odd bug.
在C(和C ++)中,数据类型为''int''和''enum''部分是类型安全的。例如:
In C (and C++), the datatypes ''int'' and ''enum'' are partly typesafe. For example:
typedef enum {E0 = 0, E1 = 1} ENUMtype_t;
ENUMtype_t e = E0; // legal
int i = 0; // legal
i = E0; // legal
e = 0; // legal(!)
e = 1; // error(!)
e = i; // error
e = (ENUMtype_t) i; // legal
这篇关于gcc将int *转换为枚举*错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!