Declaring functions and variables multiple times in C++

4.3k views Asked by At

In C++, declaring a variable multiple times shows an error during compilation. For example:

int x;
int x;

While declaring a function multiple times doesn't show any error during compilation. For example:

int add(int, int);
int add(int, int);

Why is this distinction in C++?

1

There are 1 answers

5
leslie.yao On BEST ANSWER

Note that int x; is not (just) declaration, it's definition. So error arisen since ODR is violated, i.e. only one definition is allowed in one translation unit.

A declaration of variable could be written as:

// a declaration with an extern storage class specifier and without an initializer
extern int x;
extern int x;

In the meantime int add(int, int); is a declaration (of function) exactly. Multiple declarations in one translation unit are fine, ODR is not violated.