Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating struct variable using the tag name

I have read a article in the following link

http://www.embedded.com/electronics-blogs/programming-pointers/4024450/Tag-vs-Type-Names

Here author says that, use of follwing is wrong.

struct s
{
--
};

s var;

But in my sample code its works perfectly.

  1 #include<iostream>
  2 using namespace std;
  3
  4 struct s
  5 {
  6    int sd;
  7 };
  8 s v;
  9
 10
 11
 12 int main()
 13 {
 14
 15    v.sd=10;
 16    cout<<v.sd;
 17    return 0;
 18 }

EDIT:

What the actual difference? why it works in c++ and not works in c;

like image 344
VINOTH ENERGETIC Avatar asked Jan 06 '14 14:01

VINOTH ENERGETIC


People also ask

What is tag name in struct?

An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type. A variable of that structure type holds the entire sequence defined by that type. Structures in C are similar to the types known as "records" in other languages.

How do you declare a struct variable in C++?

How to declare a structure in C++ programming? The struct keyword defines a structure type followed by an identifier (name of the structure). Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure.

Can struct name be same as variable name?

Yes, that is perfectly fine.

How do you declare 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. */ }; Here tag_name is optional in some contexts.


Video Answer


2 Answers

It is the difference between C++ and C. The author you are citing speaks about C while you use C++ code instead of C code. In C you have to specify keyword struct, union or enum before declaring variables of correspondings types.

like image 59
Vlad from Moscow Avatar answered Oct 18 '22 05:10

Vlad from Moscow


The article says that a user-defined type using

struct s {
   ...
};

defines a tag name s. To name the actual type, you can write struct s (C or C++) or class s (C++ only), but C++ makes both keywords optional (and almost never actually used). So whenever you write s in C++ it's actually interpreted as the correct type, while in C the keyword is obligatory to name the type.

So long story short: in C++ there is no difference in writing struct s, class s or s, they all mean the same.

In order to define the type name s in a C/C++ shared header, one typically writes

typedef struct {
   ...
} s;

Then the type s can be used in both C and C++ without the need to write struct.

like image 22
leemes Avatar answered Oct 18 '22 04:10

leemes