signed and unsigned data types
Primitive Data Types
ประเภทตัวแปรพื้นฐานในภาษา C++ มีดังนี้
Integer (int)ใช้สำหรับเก็บข้อมูลประเภทตัวเลขจำนวนเต็ม
Character (char) ใช้สำหรับเก็บข้อมูลประเภทตัวอักษร
Boolean (bool) ใช้สำหรับเก็บข้อมูลเพียงสองค่าคือ true และ false
Floating point (float)ใช้สำหรับเก็บข้อมูลประเภทตัวเลขทศนิยม
Double Floating Point ใช้สำหรับเก็บข้อมูลประเภทตัวเลขทศนิยม โดยมีพื้นที่การเก็บมากกว่าตัวแปร float สองเท่า
Valueless (Void) ใช้สำหรับค่าว่างเปล่า
Wide Character ช้สำหรับเก็บข้อมูลประเภทตัวอักษร unicode
Data type modifiers
เราสามารถใช้คำสั่งด้านล่างนี้ในการกำหนดเพิ่มลดขนาด(Size)และกำหนดช่วงข้อมูล(Range) ในพื้นที่หน่วยความจำและการรับข้อมูลสำหรับเก็บค่าตัวแปร
Signed ใช้สำหรับกำหนดช่วงข้อมูลของตัวแปรให้สามารถรับค่าช่วงข้อมูลตัวเลขที่เป็นจำนวนลบได้
Unsigned ใช้สำหรับกำหนดช่วงข้อมูลของตัวแปรให้สามารถรับค่าช่วงข้อมูลที่ 0 ขึ้นไป จะไม่สามารถรับข้อมูลตัวเลขที่เป็นจำนวนลบได้
Short ใช้สำหรับกำหนดขนาดตัวแปร int ให้ใช้พื้นที่ลดลงเหลือ 4 bytesเป็น 2 bytes เหมาะกับข้อมูลตัวเลขที่ไม่เยอะมาก
long ใช้สำหรับกำหนดขนาดตัวแปร int ให้ใช้พื้นที่เพิ่มขึ้นจาก 4 bytes เป็น 8 bytes เหมาะกับข้อมูลตัวเลขที่ไม่เยอะมาก
Data Type | Size (in bytes) | Range |
short int | 2 | -32,768 to 32,767 |
unsigned short int | 2 | 0 to 65,535 |
unsigned int | 4 | 0 to 4,294,967,295 |
int | 4 | -2,147,483,648 to 2,147,483,647 |
long int | 8 | -9.223372e+18 to 9.223372e+18 |
unsigned long int | 8 | 0 to 18,446,744,073,709,551,615 |
long long int | 8 | -9.223372e+18 to 9.223372e+18 |
unsigned long long int | 8 | 0 to 18,446,744,073,709,551,615 |
signed char | 1 | -128 to 127 |
unsigned char | 1 | 0 to 255 |
float | 4 | 1.2E-38 to 3.4E+38 |
double | 8 | 2.3E-308 to 1.7E+308 |
void | - | - |
wchar_t | 2 or 4 | 1 wide character |
สร้าง file.cpp ชื่อว่า sizeData.cpp แล้วคัดลอก code ด้านล่างลงไฟล์ที่สร้าง
ทดลอง complier และ run โปรแกรม
Output :
คำสั่ง sizeof() ใช้สำหรับตรวจสอบขนาดพื้นที่หน่วยความจำที่ตัวแปรใช้ มีหน่วยเป็น Byte
ตัวอย่าง ความแตกต่างของข้อมูล unsigned int and int
ทดลอง complier และ run โปรแกรม
สร้าง file.cpp ชื่อว่า rangeData.cpp แล้วคัดลอก code ด้านล่างลงไฟล์ที่สร้าง
ทดลอง complier และ run โปรแกรม
Output:
แหล่งอ้างอิง
Last updated