NaveeNeo NaveeNeo - 28 days ago 8
C Question

When typedef is used in C, will it create a new type or only a type name?

#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;
}



Here in this example, Book is a new Data type or its just an alternate name to structure?


or in other words if the code is :
typedef unsigned char newDType;

newDType
is a new data type or alternate name to
unsigned char
?

Answer

From the typedef specifier msdn page (click to know more)

A typedef declaration introduces a name that, within its scope, becomes a synonym for the type given by the type-declaration portion of the declaration.


So, as quoted the new name is just an alternative name(synonym) for the original type. Generally, typedef declarations are used to make declarations more uniform and compact.