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

Type difference of character literals in C and C++


ใน C++ ขนาดของ character constants เป็น char ใน C ชนิดของ character constant เป็น integer (int) ดังนั้นใน C sizeof('a') เป็น 4 สำหรับ 32-bit architecture และ CHAR_BIT เป็น 8 แต่ sizeof(char) เป็น 1 byte ทั้ง C และ C++

ตัวอย่าง

#include<stdio.h> main() {    printf("%d", sizeof('a')); }

ผลลัพธ์

4

ตัวอย่าง

#include<iostream> using namespace std; main() {    cout << sizeof('a'); }

ผลลัพธ์

1

ทั้งสองกรณีทำเหมือนกัน แต่ใน C sizeof('a') คืน 4 เพราะถูกถือเป็น integer ใน C++ คืน 1 เพราะถือเป็น character