Sayalic
Sayalic

Reputation: 7650

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

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?

Upvotes: 7

Views: 155

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69902

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.

Upvotes: 14

Related Questions