Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested structures in C and C++

Tags:

c++

c

Is there any significance behind allowing the visibility of nested structures outside the structure in C but not in C++? I did not find any reference or relevance.

struct a {   struct b{   }; };  int main(){   struct b var;  // allowed in C not in C++. } 
like image 651
nikel Avatar asked Nov 27 '11 07:11

nikel


People also ask

Does C support nested structures?

C provides us the feature of nesting one structure within another structure by using which, complex data types are created. For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code.

What is structure structure in C?

Syntax to Define a Structure in CstructName: This is the name of the structure which is specified after the keyword struct. data_Type: The data type indicates the type of the data members of the structure. A structure can have data members of different data types.

What is the syntax of nested structure?

Here is the syntax to create nested structures. structure tagname_1 { member1; member2; member3; ... membern; structure tagname_2 { member_1; member_2; member_3; ... member_n; }, var1 } var2; Note: Nesting of structures can be extended to any level.

What is the advantage of nested structure?

The advantage of using this type of structure declaration is that we can declare a variable of type struct man anywhere throughout the program. Note: Nesting of structure within itself is never allowed. Let's see an example of how nesting of structure within itself is not allowed.


1 Answers

It is valid in C because C has a single namespace in which all nonlocal types (i.e., types not declared in functions) are defined; there is no scoping of types using namespaces or nesting.

In C++, type b is nested as a member of class a, so its name must be qualified with the scope in which it is declared.

like image 150
James McNellis Avatar answered Sep 26 '22 08:09

James McNellis