Home > Backend Development > C++ > Why Does the Same Code Print 'hello' in C and Nothing in C ?

Why Does the Same Code Print 'hello' in C and Nothing in C ?

Mary-Kate Olsen
Release: 2024-11-09 16:25:03
Original
770 people have browsed it

Why Does the Same Code Print

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");
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template