Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

types

typedef

#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?

like image 607
NaveeNeo Avatar asked Nov 11 '16 19:11

NaveeNeo


People also ask

Does typedef create a new type?

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.

Why do we use typedef in C?

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.

What is the use of typedef in C with example?

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.

When should we use a typedef?

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.


1 Answers

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.

like image 99
Keith Thompson Avatar answered Sep 25 '22 02:09

Keith Thompson