Hari Krishnan
Hari Krishnan

Reputation: 6302

Is it optional to use struct keyword before declaring a structure object?

To declare a class object we need the format

classname objectname;

Is it the sameway to declare a structure object?

like

structname objectname;

I found here a structure object declared as

struct Books Book1;

where Books is the structure name and Book1 is its object name. So is there any need of usinge the keyword struct before declaring a structure object?

Upvotes: 18

Views: 10085

Answers (3)

Sajad
Sajad

Reputation: 524

You have to typedef them to make objects without struct keyword

example:

typedef struct Books {
     char Title[40];
     char Auth[50];
     char Subj[100];
     int Book_Id;
} Book;

Then you can define an object without the struct keyword like:

Book thisBook;

Upvotes: 13

Rohit Takhar
Rohit Takhar

Reputation: 105

Yes. In case of C language, you need to explicitly give the type of the variable otherwise the compiler will throw an error: 'Books' undeclared.(in the above case)

So you need to use keyword struct if you are using C language but you can skip this if you are writing this in C++.

Hope this helps.

Upvotes: 6

Dietrich Epp
Dietrich Epp

Reputation: 213338

This is one of the differences between C and C++.

In C++, when you define a class you can use the type name with or without the keyword class (or struct).

// Define a class.
class A { int x; };

// Define a class (yes, a class, in C++ a struct is a kind of class).
struct B { int x; };

// You can use class / struct.
class A a;
struct B b;

// You can leave that out, too.
A a2;
B b2;

// You can define a function with the same name.
void A() { puts("Hello, world."); }

// And still define an object.
class A a3;

In C, the situation is different. Classes do not exist, instead, there are structures. You can, however, use typedefs.

// Define a structure.
struct A { int x; };

// Okay.
struct A a;

// Error!
A a2;

// Make a typedef...
typedef struct A A;

// OK, a typedef exists.
A a3;

It is not uncommon to encounter structures with the same names as functions or variables. For example, the stat() function in POSIX takes a struct stat * as an argument.

Upvotes: 31

Related Questions