Solved

What is the difference between declaring a STRUCT and declaring a typedef STRUCT ?

Posted on 2004-04-26
13
2,972 Views
Last Modified: 2013-12-14
What is the difference between doing these two things?

typedef struct
{
      D3DXVECTOR3          vPosition;
      float            pointsize;
      D3DCOLOR      color;
}      VERTEX_PARTICLE;


or

struct VERTEX_PARTICLE
{
      D3DXVECTOR3          vPosition;
      float            pointsize;
      D3DCOLOR      color;
}



Thanks!
0
Comment
Question by:oxygen_728
  • 2
  • 2
  • 2
  • +7
13 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 320 total points
ID: 10925817
adding a typedef makes the struct a user defined type ....

you can then declare variables of this type just in the same way as you would declare for built in types
e.g. ITEMS item1, item2;

without the typedef, the declaration would be something like
struct ITEMS item1, item2;

0
 
LVL 10

Assisted Solution

by:Sys_Prog
Sys_Prog earned 40 total points
ID: 10925826
There is no difference in case of C++

In C
when u declared a  struct,
for example
struct A {
     int i ;
} ;

While declaring an object of this struct, u had to use
struct A obj1 ;

However in C++, this is not required, u can directly use
A obj1 ;

typedef is just a mechanism to make an alias of a type
Hence, in your case
the typedef would just alias the defined struct to VERTEX_PARTICLE

Amit



0
 
LVL 45

Assisted Solution

by:sunnycoder
sunnycoder earned 320 total points
ID: 10925831
0
 
LVL 3

Assisted Solution

by:CoolBreeze
CoolBreeze earned 20 total points
ID: 10925834
not much difference. you should look at typedef and struct differently.
usually you do this:

struct structure_name
{
  // struct variables
};

in fact you can also do it this way:

struct
{
  // struct variables
};

just that you can't really reference this structure.
now looking at typedef, you can use typedef this way:

typedef int abc;

now you can do something like:

abc i;

similarly, it is the same idea here. you do something like:

typedef struct
{
  // struct_variables
} abc;

and abc is a new typedef for the structure. what is in place there between typedef and
abc is just a type, it can be a simple data type like int or a type like structure.
0
 
LVL 1

Assisted Solution

by:hal3000
hal3000 earned 20 total points
ID: 10925845
Hi oxygen_728,

Main difference is the way that you use the type definition in a variable declaration

To declare a variable x using the typedef you would say
    VERTEX_PARTICLE x;

To declare the variable using only the struct definition you would have to say
    struct VERTEX_PARTICLE x;

Note you also left out a semicolon at the eend of your struct definition.

Good luck
0
 
LVL 10

Assisted Solution

by:Sys_Prog
Sys_Prog earned 40 total points
ID: 10925867
hal3000,

As my previous post suggests, that is NOT for C++ ,  It is true in case of C

Amit
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 4

Assisted Solution

by:PerryDK
PerryDK earned 20 total points
ID: 10926006
as most people have already stated there is no differnce.  Just to add something to the conversation to clarify when the typedef is usefull

typedef unsigned char MY_BYTE;

MY_BYTE is somewhat more meaningfull than unsigned char.  In fact some header files actually do this and declare a unsigned char as byte or BYTE.  The purpose of this is just to clarify that your not really dealing with a char but the data is a BYTE of data.  

typedef is also used when typing out the type is long and tedious for instance consider this

typedef std::map<int, double> MY_MAP;
typedef MY_MAP::iterator MY_ITERATOR;

MY_MAP map;
//fill up map
MY_ITERATOR i = map.begin();
while(i != map.end())
{
  //do something with i
  i++
}

if you didn't use the typedef the code would look like this which isn't as pretty :)
std::map<int, double> map;
//fill up map
std::map<int, double>::iterator i = map.begin();
while(i != map.end())
{
  //do something with i
  i++
}

now imagine that in your code you use the type
std::map<int, double>::iterator
in quite frequently in your code...it much easier and more descriptive to use
MY_ITERATOR i;
rather than
std::map<int, double>::iterator i

all over in the code.  Especially if you name MY_ITERATOR something meaning full.



typedef  can also be used to maintain code easier if a type needs to be changed consider this simple server code

typedef unsigned char ID_TYPE;

ID_TYPE commandID;
ID_TYPE responseID;

read(commandID);
if(commandID == 0)
  //process and figure out what response is
  send(responseID);
else if(commandID = 1)
 //process and figure out what response is
  send(responseID);


ok your going along and all of sudden you reach commandID 255 or responseID 255.  Your code uses the ID_TYPE commandID and ID_TYPE responseID all over your code.  So now your boss says we need more commands.  Ok so we could use an unsigned short instead of unsigned char.  Now all we do is change one line of code

typedef unsigned short ID_TYPE;
instead of
typedef unsigned char ID_TYPE;

if you hadn't used the typedef it could take you a day or longer to search through all your code and figure out where you are declaring an ID that needs be changed to a short instead of char.  Whoops now your program doesn't work correctly...after a day of debuggging you find out you missed one of the ID's that should have been declared as a unsigned short instead of an unsigned char.  Using typedef save you the hassel of this nightmare.

portability is also a good usage of typedef.  For instance you might be writing software that will be used on a micro process that only supports 16 bit integers and a computer that supports 32 bit integers.

class MY_32_BIT_INTEGER
{
  //implement a 32 bit integer using two 16 bit integers
};

when compiling for the 16 bit micro processer use
typedef MY_32_BIT_INTEGER MY_INT;

when compiling for the other computer just change that line to
typedef int MY_INT;

when ever you use a 32 bit integer in your code use MY_INT instead of int ensuring that your code is easily portable from one platrform to another.


I can't think of any more common or good usages of typdef but thats all that I can think of at the moment.
0
 
LVL 7

Assisted Solution

by:vijay_visana
vijay_visana earned 20 total points
ID: 10926077
Use of the typedef specifier with class types is supported largely because of the ANSI C practice of declaring unnamed structures in typedef declarations. For example, many C programmers use the following:

typedef struct    // Declare an unnamed structure and give it the
{                 //  typedef name POINT.
    unsigned x;
    unsigned y;
} POINT;

The advantage of such a declaration is that it enables declarations like:

POINT ptOrigin;

instead of:

struct point_t ptOrigin;

In C++, the difference between typedef names and real types (declared with the class, struct, union, and enum keywords) is more distinct. Although the C practice of declaring a nameless structure in a typedef statement still works, it provides no notational benefits as it does in C.

In the following code, the POINT function is not a type constructor. It is interpreted as a function declarator with an int return type.

typedef struct
{
    POINT();         // Not a constructor.
    unsigned x;
    unsigned y;
} POINT;

The preceding example declares a class named POINT using the unnamed class typedef syntax. POINT is treated as a class name; however, the following restrictions apply to names introduced this way:

The name (the synonym) cannot appear after a class, struct, or union prefix.


The name cannot be used as constructor or destructor names within a class declaration.
In summary, this syntax does not provide any mechanism for inheritance, construction, or destruction.

0
 
LVL 17

Assisted Solution

by:rstaveley
rstaveley earned 20 total points
ID: 10926615
Nice destinction, vijay_visana, but beware that if you try to compile...

typedef struct
{
    POINT();         // Not a constructor.
    unsigned x;
    unsigned y;
} POINT;

...with GNU's g++, you get the error message...

        ISO C++ forbids declaration of `POINT' with no type

You'd need to specify the return type to be compliant.

The following illustrates your point:
--------8<--------
#include <iostream>

typedef struct
{
    int POINT();        // Obviously not a constructor
    unsigned x;
    unsigned y;
} POINT;

struct POINT2
{
    POINT2();           // Is a constructor.
    unsigned x;
    unsigned y;
};

int POINT::POINT() // This is a function, but your C++ instincts should tell you this looks odd
{
        std::cout << "POINT() function for POINT called\n";
        return 0;
}

POINT2::POINT2() // This is a good old fashioned ctor for POINT2
{
        std::cout << "ctor for POINT2 called\n";
}

int main()
{
        POINT p;
        p.POINT();

        POINT2 p2;
}
--------8<--------
0
 
LVL 12

Assisted Solution

by:stefan73
stefan73 earned 20 total points
ID: 10926791
Hi oxygen_728,
The only difference is about symbol name spaces (not the same as C++ name spaces!).

As C/C++ do not support strong types with typedef (they can still be substituted by the underlying type for anything), typedef is more like providing an "alias" for an existing type, so that

typedef struct {
    int a,b,c;
} sx;

typedef struct {
    int a,b,c;
} sy;

sx my_abc;
sy my_abc2;


is the same as

struct {
    int a,b,c;
} my_abc,my_abc2;

... so the two types are not distinct: If you write a function which accepts sx as parameter, you can also provide sy.

But if you define

struct sx{
    int a,b,c;
};

struct sy{
    int a,b,c;
};


you create two distinct types. If you write a function which accepts sx as parameter, you cannot provide sy, as this will be considered something different.


Cheers,
Stefan
0
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 20 total points
ID: 10927491
I think it's a historical artifact.... Probably struct was added to C long before typedef.

So the type-name in the  struct definition is a bit more "primitive" than the one in a typedef, in that you have to say "struct" before each use of it to remind the compiler you're talking about a struct, not some other name.

I'd avoid the "old style" declaration, the typedef one is a bit less clumsy.

Unfortunately there are bazillions of books and programs out there that use the old-style declaratiojn, so it's not going to go away any time soon.

0
 
LVL 12

Expert Comment

by:stefan73
ID: 10927827
grg99,
Depending on your debugger, it makes sense to combine both:

typedef struct abc_s{
    int a,b,c;
} abc;

...otherwise the debugger won't show you which type your struct is, but will show you the anonymous struct instead. Not good.

Stefan
0
 

Author Comment

by:oxygen_728
ID: 10930887
Thank you all for your time, I completely understand now!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org (http://seleniumhq.org) Go to that link and select download selenium in the right hand columnThat will then direct you to their downlo…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now