Word Count: 363
  • Post category:C
  • Post last modified:2023-01-09

Reference

Tutorial Point – C Tutorial

typedef

typedef is used to give a type a new name. Following is an example to define a term BYTE for one-byte numbers −

typedef unsigned char BYTE;

After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example..

BYTE  b1, b2;

By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows −

typedef unsigned char byte;

You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −

#include <stdio.h>
#include <string.h>
 
typedef struct Books {
   char title[50];
   char author[50];
   char subject[100];
   int book_id;
} Book;
 
int main( ) {

   Book book;
 
   strcpy( book.title, "C Programming");
   strcpy( book.author, "Nuha Ali"); 
   strcpy( book.subject, "C Programming Tutorial");
   book.book_id = 6495407;
 
   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);

   return 0;
}

typedef vs #define

#define is a C-directive which is also used to define the aliases for various data types similar to typedef but with the following differences −

  • typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc.
  • typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.

stdint.h Header File

This header file uses typedef to provide some useful integer data types:

tyedef typedata type in CStorage sizeValue range
int8_tchar1 byte-128 to 127 or 0 to 255
uint8_tunsigned char1 byte0 to 255
int16_tshort2 -32,768 to 32,767
uint16_tunsigned short20 to 65,535
int32_tint4 bytes −2,147,483,648 to  2,147,483,647
uint32_tunsigned int4 bytes0 to 4,294,967,295
int64_t long8 bytes or (4bytes
for 32 bit OS)
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
uint64_t unsigned long8 bytes0 to 18,446,744,073,709,551,615