Not logged in, Join Here! or Log In Below:  
 
News Articles Search    
 

 Home / General Programming / Strange typedef Account Manager
 
Archive Notice: This thread is old and no longer active. It is here for reference purposes. This thread was created on an older version of the flipcode forums, before the site closed in 2005. Please keep that in mind as you view this thread, as many of the topics and opinions may be outdated.
 
Mystagogue

April 15, 2005, 01:39 PM

This looks strange to me:

  1.  
  2. typedef struct foo
  3. {
  4.   int i;
  5.   int j;
  6. } foo;
  7.  

I can't figure if "foo" is supposed to be a variable or a type. It looks like it is being used both ways, and I figure that should be illegal. To make matters worse, the second occurence of "foo" would normally be the variable, but since it is the last part of a typedef, then I figure its a type. Can somebody explain, part for part, what the above typedef is actually telling the compiler?

-Brent

 
Chris

April 15, 2005, 01:44 PM

Firstly there is

typedef

which basically gives a (possibly complex) existing type declaration a new name.


here is a C++ -style struct declaration

  1.  
  2. struct foo
  3. {
  4.   int i;
  5.   int j;
  6. }
  7.  

which creates a structured type named foo.


Then wrapped around that declaration is a
  1.  
  2. typedef foo foo;
  3.  

which gives the now existing type foo the "new" name foo -- this does nothing.

 
lordcontrary

April 15, 2005, 01:58 PM

chris is right...

I usually see the code like this however...

  1.  
  2. typedef struct _foo
  3. {
  4.   int i;
  5.   int j;
  6. } foo;
  7.  


Works the same, but makes it obvious _foo & foo are not the EXACT same animal. foo is then used as your type.


 
grelle

April 15, 2005, 03:16 PM

To declare a variable of a structure type in C you have to do:
"struct foo bar;"
However, if you typedef "struct foo" too "foo" you can write it like this:
"foo bar;"

That's the reason for the typedef. It's the standard way to define structures in C.

 
Chris

April 15, 2005, 03:46 PM

In Microsoft code you used to see

  1.  
  2. typedef struct TAGfoo
  3. {
  4.   // ...
  5. } foo;
  6.  

 
Patrick Grawehr

April 18, 2005, 03:12 AM

Is my assumption right that this kind of definition is not needed in C++?
If I'm right, you can declare a variable of a "struct foo" always using
"foo bar" when using C++, even without that typedef around it.

 
Chris

April 18, 2005, 03:22 AM

Yes, you can. It was used as a C shortcut to avoid having to write "struct foo" all the time.

 
This thread contains 7 messages.
 
 
Hosting by Solid Eight Studios, maker of PhotoTangler Collage Maker.