May 11, 2021 C
The C language provides the typedef keyword, which you can use to get a new name for the type. The following example defines a term BYTE for single-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, capital letters are defined to remind the user that the type name is a symbolic abbreviation, but you can also use lowercase letters, as follows:
typedef unsigned char byte;
You can also use typedef to get a new name for a user-defined data type. For example, you can use typedef to define a new data type for a structure, and then use that new 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;
}
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
#define is the C directive, which defines aliases for various data types, similar to typedef, but they have the following differences:
Here #define simplest use of the following:
#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