Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: is function re-declaration a undefined behavior?

Tags:

c++

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:

  1. Is int f(int x = 1); a declaration or definition?
  2. Is function re-declaration like that a undefined behavior?
like image 385
Sayakiss Avatar asked Jun 30 '16 14:06

Sayakiss


People also ask

What is undefined behavior in C?

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

What is function declaration in C programming?

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 ().

What does it mean when a pointer is undefined?

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.

What happens if a function returns to its caller?

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:


1 Answers

From §8.3.6 in dcl.fct.default :

  1. 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.

like image 75
Richard Hodges Avatar answered Sep 30 '22 18:09

Richard Hodges