#### Archived

This topic is now archived and is closed to further replies.

# Typedef?

This topic is 6212 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I was looking through the tutorials section, and came accross the following code:
  typedef struct MAPDATA_type { int xMax, yMax; // map size in tiles int xCamera, yCamera; // camera location in pixels int xMaxCamera, yMaxCamera; // max camera coordinates int nNPCCount; // number of NPCs int nScriptCount; // number of linked scripts LPNPC lpnpc; // linked NPCs LPSCRIPT lpscr; // linked scripts } MAPDATA, FAR* LPMAPDATA; 
huh? i dont get it. Did i mention my c/c++ book really sucks? It doesnt cover anything like this, and i''d kind-of like to know what it is, does, is used for, can be used for, etc... please...

##### Share on other sites
typedef defines a synonym for another type. It doesn''t create a new type, just an alias to an existing one. Like:

typedef unsigned long ulong;ulong ul; // Equivalent to "unsigned long ul;"

When you see a "typedef struct ...." you are defining a structure, and declaring aliases for it in the same block of code. Like:

typedef struct my_struct_tag{ int i; float f; char c;} my_struct, *pmy_struct;my_struct s; //declares a variable of type my_struct_tagmy_pstruct ps; //declares a pointer to a variable of type my_struct_tag

##### Share on other sites
i''m confused. slightly less than before though.

so if i declared a variable:

my_struct s;

what would ''s'' be? an integer? a float? a char? an array? all three (int float and char) combined into one??? in other words, whats the purpose of declaring variables inside it? and, assuming i had one, what would i do with the variables declared inside?

i''m downloading a c++ tutorial now, so maybe that will clear some stuff up... i sure wish my book included this stuff ...

##### Share on other sites
Wow, your book must REALLY suck.

quote:
Original post by Tsu
what would 's' be?

It would be a structure of type my_struct (or, technically, my_struct_tag, but let's not confuse the issue).

quote:
Original post by Tsu
all three (int float and char) combined into one??? in other words, whats the purpose of declaring variables inside it? and, assuming i had one, what would i do with the variables declared inside?
...
Whats a structure???

These are all related, so... you basically defined a structure with "all three combined into one". It's a convenient way to create a complex data type, containing a number of variables that are usually related.

This is probably a little more complicated than what can be explained in a post, but if you look at the example you posted, you have a structure holding information about a map. If you look at the fields within the structure (nNPCCount, etc.), notice that they all are things you might want to know about a map. Since all these things are specific to ONE particular map, it's convenient to group them all together, rather than have a bunch of independent variables. Why is this convenient? Because you can declare an instance of MAPDATA (ie. a variable of type MAPDATA) like this:

MAPDATA map;

and then use map to access the fields within it, using the . (dot) operator; eg.

map.nNPCCount = 100;

if (map.nScriptCount)
...

etc.

In C++, structs become even more powerful, but again, I don't want to confuse the point.

Down with Tiberia!

##### Share on other sites

Anyway, a structure is just what it sounds like, it is a programming construct that is made up of other subcomponents. When you start talking about structures, you''re ''beginning'' to enter the realm of object oriented design. A few simple examples are:

struct CAR{int nMaxSpeed;int nFuelCapacity;char szName[32];};struct PERSON{char szName[64];int nAtheleticAbility;int nIQ;int nYearlySalary;int nAge;}

Each of the components IN a structure define that structure. Structures may contain properties only. Classes have the ability to also ''contain'' functions. Get comfortable with structures first, then take a little look at classes if you get curious, but it''s important to understand structures first.
};

##### Share on other sites
quote:
Original post by JonStelly

Structures may contain properties only. Classes have the ability to also ''contain'' functions.

Actually, that''s not true. In C++, structs can be used exactly like classes. The only difference is that the members of a struct are public by default, while the members of a class are private.

##### Share on other sites
Shhh, you''re confusing my point. =p

##### Share on other sites
yes, my book does really suck ... kind-of. it does explain most other things in detail (4 chapters on classes), but i think it was made to be at a ''beginners'' level (although it doesnt say it), which is probably why i bought it (okay, my parents bought it, but i picked it out ) in the first place. That and it was within my price range at the time. I guess you get what you pay for then.
i''m getting off topic...

quote:
Original post by JonStelly

Sorry to mislead anyone, but i didnt / don''t know the difference. (yet!)

quote:
Original post by JonStelly
Get comfortable with structures first, then take a little look at classes if you get curious, but it''s important to understand structures first.
When you start talking about structures, you''re ''beginning'' to enter the realm of object oriented design.

My book goes straight from strings and string related functions to classes. Its a bit confusing (to say the least).yes, i do plan on buying a better book(s) (as soon as i have some money )

BACK TO STRUCTS
So its kind-of like a database, (using my knowledge of MS Access as example here) where you have your table (MAPDATA), and the fields within the table(int xMax, etc)? but your only dealing with one record at a time (the var you assign to be a MAPDATA). or am i completely lost?

And i''m still a bit sketchy about typedefs... they just make an ''alias'' to the struct (using the first example)? is this almost the same as:
  #DEFINE BOB 42;...rectfill (buffer,BOB,...);

where wherever it finds ''BOB'', it replaces it with ''42''?

i guess what i should be asking is, what is meant by aliases?

  typedef struct my_struct_thing{ int x; int y; int q; char k[100]; //just for fun...}...my_struct_thing bob;...bob.x = 64;bob.y = 9;printf ("Bob has this much x: %d ", bob.x);

OUTPUT: Bob has this much x: 64
Correct?
if yes: YAY! i learned something!

i noticed that you (JonStelly) put a ''n'' in front of all your vars in the CAR and PERSON example (int nIQ. is that just for your own reference, or does that tell it its a number or something?

and finally, whats ''..} my_struct, *pmy_struct;..''? this is a slightly less important question, as i''m learning structs now, but i''m still curious...

##### Share on other sites
Ah, lots of questions...

First, to recomend a book that I really like / liked. It''s a great beginner / intermediate book called "Object Oriented Programming in C++" by The Waite Group.

Struct like a DB Table - Pretty Much... If thinking of them that way helps you, it''s close enough to the truth for now. Anything to help you visualize what you''re learning is a good thing IMHO.

typedef - The typedef code you''ve been looking at defines a structure and also creates the aliases. Let me simplify the example a bit by changing to a built-in type:

  typedef unsigned long u_long;u_long ulA;unsigned long ulB;

All the typedef does is give you another way to refer to the type. You could have done the same thing using:

  #define u_long (unsigned long)

but #define is EVIL, and with typedef, the compiler can perform some basic checks to make sure what you''re doing makes sense.

Variable Names - I use a modified version of "hungarian notation". It''s a system of naming your variables so that you can tell not only what they are used for, but also what type they are just by the name. Some examples:

char - cVariable //character
char[] - szVariable //string
char * - lpszVariable //pointer to a string
int - nVariable //integer
int * - pnVariable //pointer to an integer
float - fVariable //floating point integer
float * - pfVariable //pointer to a floating point integer
SYSTEMTIME * - pstCurrent //pointer to a SYSTEMTIME structure

and there are many more. I got used to it while I was learning how to program, and a lot of the microsoft samples etc... use it, which is my primary field, so I''ve just adopted my own style.

##### Share on other sites
thanks for the book recommend, i''m shopping for it right now in fact...

*Mental note: #DEFINE is evil... gotcha ...

ok, i think i get it now... thanks alots...

so then would this work?:
  typedef char[256] string;string my_string;

##### Share on other sites
http://www.edm2.com/0408/introc1.html

a very good intro to C, it is only 30 pages but it is about equivilent to a semester

##### Share on other sites
Tsu, #define is NOT evil. There are many legitimate reasons for using #define and other preprocessor directives.

For example:

1. Stopping the redefinitions when including the same header file in two different files
2. Creating code that does extra error checking only while in debug mode (ie, ASSERTS)
3. Using platform specific code in a multi-platform application.
4. Getting file and line numbers on errors for debugging purposes.
5. Overriding compiler specific byte alignment so your code works on all compilers.

The list goes on and on. However, you SHOULDN''T use #defines when you can do the same thing using normal C/C++ code, as in JonStelly''s example.

- Houdini

##### Share on other sites
Tsu,

I think a lot of your confusion arises from the fact that typedef and struct are used together in the example, and because of differences between C and C++.

In C you had to use the struct keyword when defining structs and declaring variables based on those structs. In C++ there is no need to include the struct keyword when declaring structure type variables. For example:

struct PERSON_TYPE{  int Age;  int Height;  char Name[64];};  struct PERSON_TYPE Player1; // This is ok in C and C++PERSON_TYPE Player2; // Illegal in C, but ok in C++

Typedef lets you assign other names to types. To save having to include the struct keyword before every declaration of a PERSON_TYPE variable you could typedef it like this:

struct PERSON_TYPE{  int Age;  int Height;  char Name[64];};  typedef struct PERSON_TYPE PERSON;  PERSON Player1;PERSON Player2;

It is possible to combine typedef and struct, defining your structure as you typedef it, which is what is happening in your MAPDATA example. My example could look like this:

typedef struct PERSON_TYPE{  int Age;  int Height;  char Name[64];}PERSON;    PERSON Player1;PERSON Player2;

However, there is no need to do this if you're using C++. You can just do this:

struct PERSON_TYPE{  int Age;  int Height;  char Name[64];};    PERSON_TYPE Player1; // This only works in C++PERSON_TYPE Player2;

Just to confuse matters, you can also include a list of variables immediately after a struct definition, like this:

struct PERSON_TYPE{  int Age;  int Height;  char Name[64];}Player1, Player2; // ok in C and C++  Player1.Age = 24;//.. etc...

Note that this is very different from the typedef example. This defines Player1 and Player2 as variables of type PERSON_TYPE.

I know it's confusing but if you're using C++ I'd suggest forgetting about typedef, other than to use it for convenience/readability sake with things like "typedef unsigned long DWORD". There's no need to use it with structs.

Hope this makes sense.

Moot

Edited by - Moot on February 15, 2001 9:20:03 AM

##### Share on other sites
Ok, if this is a repeat of anything already said, forgive me.

Alright, let''s say you have some kind of graphics function. Now, you want to pass it an x and y coordinate, to start drawing at. You also have a BUNCH of other similar functions. But, you don''t want to go to all the trouble of passing int x, int y, to every function. This is why we use structs. Probably the simplest struct you will ever see is a Point, or Coordinate struct. Typically programmers use Point. What it does is creates a new variable type called Point, that *contains* two variables called X, and Y. Check it out:

// Struct is the keyword, Point is the new variable-type-name.
struct Point
{
// X and Y are "sub-variables", usually called "members".
int X;
int Y;
};

Ok, now you have a Point type. So what do you do with it? You use it just like an int or char or any of the built-in types.

Point p;
Point q;
Point w;

But what does that get you? Well, so far, nothing. But, that''s because you don''t know how to access X and Y.

p.X = 4;
p.Y = 40;

q.X = 10;
q.Y = 11;

w.X = p.X + q.X;
w.Y = p.Y + q.Y;

So know, i think it should be clear what they do. That''s all for now.

farmersckn

##### Share on other sites
The book Object Oriented Programming in C++ is a _very_ good book for learning about this sort of thing. My thanks to you, JonStelly, for suggesting it

Tsu - Thanks for posting a question I had never even thought about before, and I hope you''ve got it figured out... Good luck

Press to test... *click* Release to detonate...

##### Share on other sites
Moot: Wow, I knew both of those things about typedef and struct in C, but I never put two and two together, so I never understood why they used all the typedef-ing.

Tsu: I can''t offer anything that hasn''t been said, but good luck learning C++!

##### Share on other sites
quote:
Tsu - Thanks for posting a question I had never even thought about before, and I hope you''ve got it figured out... Good luck

No problem! i had no idea my confusion could actually help people ... thanks

Erase Mental Note: #DEFINE is evil
Replace Mental Note: #DEFINE is evil when used improperly

so, what good is define? Houdini, you mentioned:
"Stopping the redefinitions when including the same header file in two different files"... What do you mean by that? I can make a header file that declares a variable inside it, but then it says that the variable name is already declared. Is that what you mean?

So as i see them, structs are like databases (well, one record of them anyway, depends on how you use them). Somebody, i dont remember who and am too lazy to scroll down and find out, hinted that they can be used for more than that... i''m curious.

quote:

struct PERSON_TYPE Player1;

This seems like a wierd way of declaring a variable though... wouldnt that make a new struct instead of declaring a var as one though? it just seems like it would... i''ll just switch to ''gxx'' when i compile then (i currently use ''gcc'')... would there be any problems / major differences if i do that...

RE: THAT BOOK
Hurrah for books that arent really expesive!
the ones that i could''v chosen over the one i have now where about $90 -$150... i chose the \$60 one, as i only had that much money...

##### Share on other sites
The macros that you manipulate with #define, #undef, #ifdef, #else, etc. are preprocessor macros. They are not part of the language. They are extremely common, in fact so much so that you can count on them in any C/C++ compiler.

A source file is just a text file. Those preprocessor macros just tell the compiler to skip, replace, etc. certain portions of text (not code), so they can be used to do things that you can''t normally do in code, like generate incomplete blocks of code to be used as building blocks for complex functions.

After the preprocessor is done, the compiler looks at the modified text file.

Another use for the preprocessor is conditional compilation. If you have one part of an optimized function written in code that works well on Alpha processors, then you can direct the compiler to use that code when compiling your program for Alpha processors. And you could have it use another set of code for Intel processors.

You accomplish conditional compilation by first checking for some kind of condition (say the target platform, or the version of the compiler), and then defining a symbol. Code that should or shouldn''t be compiled then checks whether or not that symbol was defined:

// included somewhere like in the project''s main header#ifdef _WINDOWS#ifndef _DLL#define WINDOWS_APPLICATION#else#define WINDOWS_DLL#endif// much later, in many many placeswindow::~window(){#ifdef WINDOWS_DLL // Requires different cleanup for DLLs UnregisterClass(...);#endif}

Tools are never evil; only misuse of tools is evil.