Declaring functions and variables several times in C ++

In C ++, declaring a variable several times shows an error at compile time. For instance:

int x; int x; 

When declaring a function, a compile-time error is not displayed several times. For instance:

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

Why is this difference in C ++?

+5
source share
1 answer

Note that int x; not (simple) declaration , definition . Thus, an error occurred after the ODR is violated, i.e. Only one definition per translation unit is allowed.

A variable declaration can be written as:

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

Meanwhile, int add(int, int); - This announcement (functions) for sure. Several declarations in one translation unit are excellent, ODR is not violated.

+12
source

Source: https://habr.com/ru/post/1262013/


All Articles