ชนิดข้อมูลแบบค่าคงที่ (Constants)
รูปแบบ
Const[ชนิดข้อมูล][ตัวแปร]=[ค่าหรือ นิพจน์]
ตัวอย่าง
const folat a = 5.23;
const int b = a%2;
โปรแกรมที่ 2-4 การใช้ตัวแปรชนิดข้อแบบค่าคงที่
#include<stdio.h>
imt main(void)
{
const float pi = 3.14159;
float radius;
radius = 3;
printf(“Value of pi : %f\n”,pi);
printf(“Value of area : %f\n”,pi*(radius*radius));
return 0;
}
imt main(void)
{
const float pi = 3.14159;
float radius;
radius = 3;
printf(“Value of pi : %f\n”,pi);
printf(“Value of area : %f\n”,pi*(radius*radius));
return 0;
}
ผลการทำงาน:
Value of pi : 3.141590
Value of area : 28.274311
constant นั้นสามารถแบ่งออกได้ ดังนี้
Integer Constants เป็นค่าคงที่ชนิดข้อมูลแบบตัวเลขจำนวนเต็มไม่มีจุดทศนิยม
const int a = 5;
Integer Constants เป็นค่าคงที่ชนิดข้อมูลแบบตัวเลขจำนวนเต็มไม่มีจุดทศนิยม
const int a = 5;
Floating-Point Constants เป็นค่าคงที่ชนิดข้อมูลแบบตัวเลขที่มีจุดทศนิยม
const float b = 5.6394;
const float b = 5.6394;
Character Constants เป็นค่าคงที่ชนิดตัวอักษร ซึ่งจะต้องอยู่ภายในเครื่องหมาย ‘’เท่านั้น
const char b = ‘t’;
const char b = ‘t’;
String Constants เป็นค่าคงที่เป็นข้อความ ซึ่งจะต้องอยู่ภายใต้เครื่องหมาย “”เท่านั้น
“”
“h”
“Hello world\n”
“HOW ARE YOU”
“Good Morning!”
“”
“h”
“Hello world\n”
“HOW ARE YOU”
“Good Morning!”
โปรแกรมที่ 2-5 การใช้ตัวแปรชนิดข้อมูลแบบค่าคงที่แบบต่าง ๆ
#includ<stdio.h>
int main(void)
{
const int a = 3; /*Integer Constats*/
const flat b = 3.14159; /*Floating – Point Constants*/
const cahr c = ‘P’; /*Character Constants*/
printf(“Value of a: %d\n”,a);
printf(“Value of b: %d\n”,b);
printf(“Value of c: %d\n”,c);
printf(“Good Bye”); /*String Constants*/
return 0;
}
int main(void)
{
const int a = 3; /*Integer Constats*/
const flat b = 3.14159; /*Floating – Point Constants*/
const cahr c = ‘P’; /*Character Constants*/
printf(“Value of a: %d\n”,a);
printf(“Value of b: %d\n”,b);
printf(“Value of c: %d\n”,c);
printf(“Good Bye”); /*String Constants*/
return 0;
}
ผลการทำงาน
Value of a : 3
Value of b : 3.141590
Value of c : P
Good Bye




