Reputation: 3
Can someone help me out? Here in the below piece of code, I am performing call by reference but with different parameter from the the function prototype, but still the program executes perfect. Could please tell me how is it possible?
struct X
{
int a;
};
void fun(struct X *b)
{
struct X c;
c=*b;
printf("%d %d",c,c.a);
}
int main()
{
struct X d;
int p;
p=20;
printf("Hello World");
fun(&p);
return 0;
}
Upvotes: 0
Views: 134
Reputation: 320631
Your code is indeed invalid. C language does not allow you to pass an int *
pointer where a struct X *
pointer is expected. Such conversion would require an explicit cast in C.
This means that your fun(&p)
call contains a constraint violation, which is what is usually referred to as "compile error". However, for reasons of backward compatibility with archaic pre-standard versions of the language many C compilers (in their default configuration) report such violations as mere "warnings" and then continue to compile the code. Continuing to compile the code is not illegal: as long as the compiler informed you about the problem, it is allowed to continue to compile. However, your program is not a valid C program and its behavior is not defined by C language.
I'm sure that in your case the compiler issued such a diagnostic message for the invalid fun(&p)
call.
It is your responsibility to look through the diagnostic messages issued by your compiler and figure out which ones indicate serious errors and which ones are "mere warnings". In some cases you can ask your compiler to help you to detect violations of language rules by issuing a "hard error" message and aborting compilation. In case of GCC or Clang this can be achieved by using -pedantic-errors
command-line option.
Upvotes: 4
Reputation: 2678
I think this can not be complied. c is s strong type language. You need make sure this is the file you are compiling.
Upvotes: 0
Reputation: 72795
Your struct is just a single integer so an integer can be cast into this structure without any problem. If you enable warnings, you'll get one but the code itself will work.These are the ones I get
foo.c: In function ‘fun’:
foo.c:10:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
printf("%d %d",c,c.a);
^
foo.c:10:5: warning: incompatible implicit declaration of built-in function ‘printf’
foo.c:10:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘struct X’ [-Wformat=]
foo.c: In function ‘main’:
foo.c:20:5: warning: incompatible implicit declaration of built-in function ‘printf’
printf("Hello World");
^
foo.c:22:9: warning: passing argument 1 of ‘fun’ from incompatible pointer type
fun(&p);
^
foo.c:6:6: note: expected ‘struct X *’ but argument is of type ‘int *’
void fun(struct X *b)
^
foo.c:16:14: warning: unused variable ‘d’ [-Wunused-variable]
struct X d;
^
If you're interested in the gory details, take a look at this.
Upvotes: -2