Difference between struct and typedef struct

Started by
0 comments, last by giant 21 years, 5 months ago
Hi. I am going through NeHe''s OpenGL tutorials and have a query. I have been programming for about 5 years now, and have been using structs for most of that time. Up to now I have always used structs as follows
  
struct VERTEX
{
     float x,y,z;
};
  
however whenever NeHe uses them it is always in the format
  
typedef struct tagVERTEX
{
     float x,y,z;
} VERTEX;
  
What is the difference between these. From what I can see they both product the exact same results, as in the structs are defined as type VERTEX and the members are accessed by name.x or name->x (if its a pointer) The way I have been using seems easier to read and understand, so what is the point in using the later. Thanks Ciaran "Only two things are infinite, the universe and human stupidity, and I''m not sure about the former." --Albert Einstein
Advertisement
The reason for this is really only apparent in C, not C++.

Back in C, if you declared a structure like this:

struct Vertex{    float x,y,z;}; 


Everytime that you made an instance of the struct or more generally just referred to its datatype, you had to actually type:

struct Vertex

so to create an instance called "MyStruct" you would have to do:

struct Vertex MyStruct;

Before I go any further, it's apparent that you don't know what the typedef keyword does. typedef is for giving a datatype another name. The way it works is this:

typedef Datatype AdditionalNameForDatatype;

Then, anytime you wanted to make an object/variable of the type "Datatype" you could use "AdditionalNameForDatatype" instead. So:

Datatype MyData;

and

AdditionalNameForDatatype MyData;

Would then be the same.

Going back to the original example of a struct -- most people feel it's unnecissary to have to type "struct " before their datatype (and rightfully so). So what you would do is typedef "struct Datatype" to some other name. That way, whenever you used the datatype, you wouldn't have to type "struct" all the time, you could just use its other name.

So, using your example:

typedef struct tagVERTEX{    float x,y,z;} VERTEX;  


This just allows people, back in C, to do things like

VERTEX MyVertex;

rather than

struct tagVERTEX MyVertex;

The reason I keep saying "in C" is because in C++, you no longer ever have to use the word struct when refering to a structure type that you create. Therefore, you'd be able to do

struct VERTEX{    float x,y,z;};  


VERTEX MyVertex;

Without the need of a typedef.



[edited by - Matt Calabrese on November 21, 2002 6:38:34 AM]

This topic is closed to new replies.

Advertisement