Typedef
'C' อนุญาตให้กำหนดชื่อประเภทข้อมูลใหม่โดยใช้คำหลัก 'typedef' การใช้ 'typedef' ทำให้เราสร้างประเภทข้อมูลใหม่ไม่ได้ แต่จะกำหนดชื่อใหม่สำหรับประเภทที่มีอยู่แล้ว
ไวยากรณ์
typedef datatype newname;
ตัวอย่าง
typedef int bhanu; int a; bhanu a; %d
- คำสั่งนี้บอกให้คอมไพเลอร์รู้จัก 'bhanu' เป็นอีกชื่อหนึ่งสำหรับ 'int'
- ‘bhanu’ ถูกใช้เพื่อสร้างตัวแปร ‘a’ อีกตัวหนึ่ง
- 'bhanu a 'ประกาศ 'a' เป็นตัวแปรประเภท 'int'
ตัวอย่าง
#include <stdio.h>
main (){
typedef int hours;
hours h; //int h;
clrscr ();
printf("Enter hours”);
scanf ("%d”, &h);
printf("Minutes =%d”, h*60);
printf("Seconds = %d”, h*60*60);
getch ();
} ผลลัพธ์
Enter hours =1 Minutes = 60 Seconds = 360
ตัวอย่างการกำหนดโครงสร้าง
typedef struct employee{
int eno;
char ename[30];
float sal;
} emp;
main (){
emp e = {10, "ramu”, 5000};
clrscr();
printf("number = %d”, e.eno);
printf("name = %d”, e.ename);
printf("salary = %d”, e.sal);
getch ();
} ผลลัพธ์
Number=10 Name=ramu Salary=5000