Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

9.7. typedef

typedef isn't much like the others, it's used to give a variable type a new name. There are two main reasons for doing this. The most common is to give a name to a struct you have defined so that you can use your new data type without having to always precede it with the struct keyword.

The second use for typedef is for compatibility. Say you want to store a 32-bit number. If you use int you are not guaranteed that it will be 32-bit on every machine. To get around this you can use preprocessor directives to selectively typedef a new type to the right size.

Example 9-2. battleships.c

#include <stdio.h>

/* type, position coordinates and armament */
struct _ship
{
  int type;
  int x;
  int y;
  int missiles;
};

typedef struct _ship ship;

int
main()
{
  ship battle_ship_1;
  ship battle_ship_2 = {1, 60, 66, 8};

  battle_ship_1.type = 63;
  battle_ship_1.x = 54;
  battle_ship_1.y = 98;
  battle_ship_1.missiles = 12;

  /* More code to actually use this data would go here */

  return 0;
}
     

 
 
  Published under the terms of the GNU General Public License Design by Interspire