1

Why am I able to pass pointers of the wrong type into C functions,
without getting either a compiler error or a warning?

//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

Cloud
  • 18,753
  • 15
  • 79
  • 153
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 5
    GCC is detecting it perfectly. And also warns about the lack of return value. Check you warning settings. – Eugene Sh. Aug 18 '15 at 16:30
  • 2
    C is not type-safe, you can do very bad things without the compiler giving you errors. It will however *warn* you, and if it doesn't then you should enable more warnings. I recommend always building with as many warnings enabled as possible, as it will tell you about things that are technically correct but that may cause problem later (for example undefined behaviors and run-time errors). – Some programmer dude Aug 18 '15 at 16:31
  • 4
    ideone won't show you warnings if there were no errors. Doesn't mean the compiler is not producing them. Add a deliberate error [and enjoy your warnings in their full glory](http://ideone.com/ADuTWU). – n. m. could be an AI Aug 18 '15 at 16:43
  • @n.m. I think your comment is a better answer than the accepted one - you should post it. – mgarciaisaia Aug 18 '15 at 17:26

1 Answers1

4

It shouldn't work. Compiling via gcc -Wall -Werror fails. From another post on SO, it's noted that Ideone uses GCC, so they're likely using very lenient compiler settings.

Sample Build


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
Community
  • 1
  • 1
Cloud
  • 18,753
  • 15
  • 79
  • 153