typedef structures

Isn't necessarily needed in C++, but has been included here for completeness.


In C, it provides a shortcut instead of having to write out the full syntax, e.g. struct myStruct { . . . } ;


Whereas in C++ typedef is implied, and therefore does not require the use of the keyword struct, thus saving a few more keystrokes and making the code look cleaner.



typedef struct identifier {

int memberOne ;

char memberTwo ;

float memberThree ;

} myStruct ;


myStruct can now be used instead of having to use the keyword, struct, before each declaration of a new structure.


#include <iostream>
using namespace std;

//declare a structure (user defined data type) called rider, with 2 objects called: smith, marquez
typedef struct rider{
	string team;
	int pos;

//function prototype called details, declaring a variable called anything of the data type rider
void details (RIDER *someLabel);

int main () {

	RIDER smith ;

	RIDER marquez={"Honda", 1} ;

	smith.team = "Monster Yamaha Tech 3" ;

	cout << smith.team << endl ;

	RIDER *ptr = &marquez ; //initialise a struct RIDER pointer to marquez

	cout << ptr->team << endl ; //display team using member pointer dereferencing; ptr->

	details(ptr) ;	//call function, sending pointer to marquez as parameter

	ptr=&smith ;	//re-define struct RIDER pointer to address of smith

	ptr->pos = 9 ;	//set pos member for smith object

	details(ptr) ;	//call function, sending pointer to smith as parameter

	return 0;

void details (RIDER *ptr) {
	cout << ptr->team;
	cout << " is in position " << ptr->pos << endl ;

Compile & Run:

Monster Yamaha Tech 3
Honda is in position 1
Monster Yamaha Tech 3 is in position 9

Leave a Reply