Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีเขียน Short Literal ใน C++

นี่คือรูปแบบ short literal ใน C++ ใน C หรือ C++ ชนิดข้อมูลต่างๆ มี literals ต่างกัน รายการด้านล่าง

Sr.No Datatypes & Literals
1int
5
2unsigned int
5U
3Long
5L
4long long
5LL
5float
5.0f
6double
5.0
7char
'\5'

มี int, long, float, double แต่ไม่มี short literal ดังนั้นไม่สามารถใช้ literal สำหรับ short ได้ แก้ได้โดย explicit typecasting

ถ้าใช้บรรทัดนี้ จะแปลงเป็น short:

int x; x = (short) 5; // แปลงเป็น short type data

ตัวอย่าง

#include <iostream>
using namespace std;

main() {
  int x;
  x = 65700;
  cout << "x is (as integer):" << x << endl;
  x = (short)65700; // จะถูกปัดหลัง 2 ไบต์
  cout << "x is (as short):" << x << endl;
}

ผลลัพธ์

x is (as integer):65700
x is (as short):164