2015-08-18 39 views
1

为什么我能够将错误类型的指针传递给C函数,
而不会收到编译器错误或警告?为什么Ideone.com C编译器不能捕获不匹配的指针类型?

//given 2 distinct types 
struct Foo{ int a,b,c; }; 
struct Bar{ float x,y,z; }; 

//and a function that takes each type by pointer 
void function(struct Foo* x, struct Bar* y){} 


int main() { 
    struct Foo x; 
    struct Bar y; 

    //why am I able to pass both parameters in the wrong order, 
    //and still get a successful compile without any warning messages. 
    function(&y,&x); 

    //compiles without warnings. 
    //potentially segfaults based on the implementation of the function 
} 

See on Ideone

+5

GCC是完全检测它。并且还警告说缺乏回报价值。检查你的警告设置。 –

+2

C不是类型安全的,如果没有编译器给你错误,你可以做很糟糕的事情。然而,它会*警告你,如果没有,那么你应该启用更多的警告。我建议始终使用尽可能多的警告进行构建,因为它会告诉您有关技术上正确但可能稍后会导致问题的事情(例如未定义的行为和运行时错误)。 –

+4

如果没有错误,ideone不会向您显示警告。并不意味着编译器不生产它们。添加一个故意的错误[并且在他们的荣耀中享受你的警告](http://ideone.com/ADuTWU)。 –

回答

4

它不应该工作。编译通过gcc -Wall -Werror失败。 From another post on SO, it's noted that Ideone uses GCC,所以他们可能使用非常宽松的编译器设置。

示例构建


test.c: In function 'main': 
test.c:15:2: error: passing argument 1 of 'function' from incompatible pointer type [-Werror] 
    function(&y,&x); 
^
test.c:6:6: note: expected 'struct Foo *' but argument is of type 'struct Bar *' 
void function(struct Foo* x, struct Bar* y){} 
    ^
test.c:15:2: error: passing argument 2 of 'function' from incompatible pointer type [-Werror] 
    function(&y,&x); 
^
test.c:6:6: note: expected 'struct Bar *' but argument is of type 'struct Foo *' 
void function(struct Foo* x, struct Bar* y){} 
    ^
test.c:19:1: error: control reaches end of non-void function [-Werror=return-type] 
} 
^ 
cc1: all warnings being treated as errors 
相关问题