Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi friends.
i have a question.
is two codes below the same?
what's the differences between the two code below?
C++
struct str
{
int a;
float b;
};

C++
struct 
{
int a;
float b;
} str;

thanks.
Posted
Comments
Richard MacCutchan 2-Oct-14 9:58am    
Take your C/C++ reference guide and read it carefully. Especially looking at the difference between a Definition and a Declaration
sara74 2-Oct-14 10:26am    
sorry but i can't find it. can you tell me?
thanks.
Mohibur Rashid 2-Oct-14 10:30am    
can't find what? the reference or the book?
sara74 2-Oct-14 10:34am    
the definition and declaration part

No, they are different.
Roughly speaking:
  • The first one declares the new type: str (much like the C typedef).

  • The second one defines the variable str, having as type the anonymous struct that precedes it.

Typically the first statement goes inside a header (.h or .hpp)
file while the second goes into a source (.cpp) one.

As suggested, grab a good C++ book in order to find more exact explanations.
 
Share this answer
 
The first case you showed
C++
struct str // str is the name of this structure definition
{
int a;
float b;
}; // no variable name so this is a definition only, no space is allocated

is the definition of a structure that can be used anywhere in your program. But as a definition it does not create anything, it just defines some information for the compiler.
In the scond case
C++
struct // no name of this definition, so it is anonymous
{
int a;
float b;
} str; // str is the name of this variable, so this is also a declaration of a variable and space will be allocated.

you have defined the structure, but also declared a variable of that structure, so space will be allocated for it in the program. Note that this is an anonymous structure (it has no structure name) so it cannot be used elsewhere.
 
Share this answer
 
Comments
sara74 2-Oct-14 11:39am    
thanks a lot my friends.
Aescleal 2-Oct-14 12:49pm    
Just a quick note: In C++ 11 you can use decltype to recover the type of str in the second code block if you need its' type somewhere else:

decltype(str) other( str );

will create another structure with the same binary layout as str and copy str into it.

edit: Forgot the greater than/less than tags to show angle brackets..
edited again: Ballsed up - decltype uses ordinary parenthesis....aaaarrrgggg
Richard MacCutchan 2-Oct-14 12:54pm    
Interesting, thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900