Latest web development tutorials

C typedef

C language provides atypedef keywords, you can use it to take a new name for the type.The following example defines a termBYTE is a single byte numbers:

typedef unsigned char BYTE;

After this type definition, it can be used as an identifier BYTEunsigned char type abbreviation, such as:

BYTE  b1, b2;

By convention, the definition will be capitalized letters in order to alert the user to type a symbolic name is an abbreviation, but you can also use lowercase letters, as follows:

typedef unsigned char byte;

You can also usetypedef to custom data types to take a new name for the user.For example, you can use the structure typedef to define a new data type, and then use this new data type to define the structure of direct variables, 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;
}

When the above code is compiled and executed, it produces the following results:

Book  title : C Programming
Book  author : Nuha Ali
Book  subject : C Programming Tutorial
Book  book_id : 6495407

typedef vs #define

C#define directive is used to define an alias for a variety of data types, and typedefsimilar, but they have the following differences:

  • typedef only symbolic names for typedefs,#define can not only define the type of alias, but also define an alias for the value, for example, you can define 1 ONE.
  • typedef is performed by the compiler interpreted,#define statement is carried out by the pre-processed by the compiler.

Here is the simplest use of #define:

#include <stdio.h>
 
#define TRUE  1
#define FALSE 0
 
int main( )
{
   printf( "Value of TRUE : %d\n", TRUE);
   printf( "Value of FALSE : %d\n", FALSE);

   return 0;
}

When the above code is compiled and executed, it produces the following results:

Value of TRUE : 1
Value of FALSE : 0