Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct with same name but different member in C++

As per book The C++ Programming Language (Bjarne Stroustrup), in section 15.2.3 (The One definition rule) page no 425, I write program as below :

file1.cpp

struct S2 { int a; char b; };

file2.cpp

struct S2 { int a; char bb; };
int main(){ return 0;}

To compile I tried below command.

g++ -std=c++11 file1.cpp file2.cpp

and

clang++ -std=c++11 file1.cpp file2.cpp

Both these command producing executable with out any error or warning. But as per book this example should give error.

like image 516
Manthan Tilva Avatar asked May 13 '16 07:05

Manthan Tilva


People also ask

Can a structure have two fields with the same name?

Yes, that is perfectly fine.

Can the structure tag name repeated?

A previously defined identifier (tag) can be used to refer to a structure type defined elsewhere. In this case, struct-declaration-list cannot be repeated as long as the definition is visible.

Can you set one struct equal to another?

Yes, you can assign one instance of a struct to another using a simple assignment statement. In the case of non-pointer or non pointer containing struct members, assignment means copy. In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

Can a struct contain another struct in C?

A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.


1 Answers

One Definition Rule says that:

if one .cpp file defines struct S { int x; }; and the other .cpp file defines struct S { int y; };, the behavior of the program that links them together is undefined.

So, your program invokes undefined behaviour (UB). So, compiler isn't required to give diagnosis for this.

If you want know the reason behind it then read this.

Hope it helps. :)

like image 128
Destructor Avatar answered Nov 15 '22 14:11

Destructor