Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct instantiation with "struct" keyword

Suppose I declare a new C++ struct type:

struct my_struct {
   int a;
   int b;
};

Can I create a new instance of this struct type by:

my_struct foo;

or

struct my_struct foo;

If both work, is there any difference?

like image 898
Paul S. Avatar asked Oct 08 '12 00:10

Paul S.


People also ask

Can struct be instantiated?

Unlike classes, structs can be instantiated without using the New operator.

Is struct keyword optional in C++?

Using a Structure In C++, you do not need to use the struct keyword after the type has been defined. You have the option of declaring variables when the structure type is defined by placing one or more comma-separated variable names between the closing brace and the semicolon. Structure variables can be initialized.

How do you initialize a struct value?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

How do you declare a struct in a struct?

The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ };


2 Answers

Yes, you can use either method. The difference is that this form:

my_struct foo;

Is not legal in C, so you must use this form:

struct my_struct foo;

Which is supported in C++ for backwards compatibility with C.

like image 200
Benjamin Lindley Avatar answered Sep 22 '22 18:09

Benjamin Lindley


Both work. The main reason the second works is compatibility with C: In C the first doesn't work. As a result, structs are typically typedefed in C and there are two different kinds of names for structs and typedefs.

like image 41
Dietmar Kühl Avatar answered Sep 19 '22 18:09

Dietmar Kühl