Behavior Differences in Valid Code Between C and C
While C and C share many similarities, there are some instances where valid code in both languages can produce different outcomes when compiled in each respective language.
Function Calling and Object Declarations
One such scenario is related to the difference in function calling and object declarations. In C90, functions can be called without being declared beforehand. In C , however, undeclared functions are not allowed. This distinction can lead to differing behavior when compiling the following code:
#include <stdio.h> struct f { int x; }; int main() { f(); } int f() { return printf("hello"); }
In C , this code will print nothing because a temporary object of type f is created and destroyed, resulting in the loss of the x member. In C90, however, it will print "hello" since functions can be called without having been declared.
Disambiguation of Names
Another point to note is the usage of the name f in the example code. Both C and C allow the use of the same name for functions and structures. To create an object in C , struct f must be explicitly specified. If the struct keyword is omitted, the code will be interpreted as a function call. This distinction, combined with the difference in calling conventions, contributes to the different behavior observed when compiling the code in C and C .
The above is the detailed content of Why Does the Same Code Print 'hello' in C and Nothing in C ?. For more information, please follow other related articles on the PHP Chinese website!