Home >Backend Development >C++ >Can Function Calls Behave Differently in C and C Despite Valid Code?

Can Function Calls Behave Differently in C and C Despite Valid Code?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 14:27:02725browse

Can Function Calls Behave Differently in C and C   Despite Valid Code?

Can Code Valid in Both C and C Behave Differently When Compiled in Each Language?

C and C share many similarities, but certain code constructs can produce different results when compiled in these languages, even if the code is syntactically valid in both.

Function Calls vs. Object Declarations

One such scenario involves function calls. In C90, functions can be called without prior declaration. However, in C , an object of type f is created when f() is called without declaration.

Example Code:

Consider the following code:

#include <stdio.h>

struct f { int x; };

int main() {
    f();
}

int f() {
    return printf("hello");
}

Behavior Differences:

  • C90: In C90, the code compiles successfully and calls the function f(), which has not been declared but can be called. It prints "hello."
  • C : In C , the code compiles but does not print "hello." Instead, it creates a temporary object of type f. As soon as the f() call is finished, the object is destroyed, so "hello" is not printed.

Version Considerations:

This behavior difference is specific to C90. In later versions of the C standard (e.g., C99), it is no longer valid to call functions without declaration. As a result, the code would behave the same in both C and C .

The above is the detailed content of Can Function Calls Behave Differently in C and C Despite Valid Code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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