Code:
#include <iostream>
using namespace std;
int f(int x = 0) {
cout << "x:" << x << endl;
return 0;
}
int main() {
f();
int f(int x = 1);
f();
return 0;
}
Output(tested on g++ 5.1):
x:0
x:1
My question:
int f(int x = 1);
a declaration or definition?Undefined behavior is a term used in the C standard. The C11 standard (ISO/IEC 9899:2011) defines the term undefined behavior as behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
Declaration: the function's name, return type, and parameters (if any) For code optimization, it is recommended to separate the declaration and the definition of the function. You will often see C programs that have function declaration above main (), and function definition below main ().
The undefined behavior happens as the pointer is converted. According to C11, if a conversion between two pointer types produces a result that is incorrectly aligned (6.3.2.3), the behavior is undefined. Here an uint32_t could require alignment of 2 or 4 for example.
If such a function does return to its caller, the behavior is undefined. In the following example, func () is declared with noreturn specifier but it returns to its caller. gcc and clang produce warnings for the above program:
From §8.3.6 in dcl.fct.default :
- For non-template functions, default arguments can be added in later declarations of a function in the same scope. Declarations in different scopes have completely distinct sets of default arguments.
Not undefined behaviour. What you're seeing is mandated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With