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;
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 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.
Yes, that is perfectly fine.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With