#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
?
Syntax. Note that a typedef declaration does not create types. It creates synonyms for existing types, or names for types that could be specified in other ways.
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.
typedef is a predefined keyword. You can replace the name of the existing data type with the name which you have provided. This keyword helps in creating a user-defined name for an existing data type. You can also use the typedef keyword with structures, pointers, arrays etc.
One good reason to use typedef is if the type of something may change. For example, let's say that for now, 16-bit ints are fine for indexing some dataset because for the foreseeable future, you'll have less than 65535 items, and that space constraints are significant or you need good cache performance.
The definitive answer to this is in the ISO C standard. N1570 is the latest draft. Section 6.7.8 paragraph 3 says:
A
typedef
declaration does not introduce a new type, only a synonym for the type so specified.
Similar wording appears in all previous editions of the C standard, and going back at least to the first edition of Kernighan and Ritchie (K&R1), published in 1978.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With