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

เขียนโปรแกรมที่ให้ผลลัพธ์ต่างกันใน C และ C++


ที่นี่เราจะดูโปรแกรมที่ให้ผลลัพธ์ต่างกันถ้าคอมไพล์ด้วย C หรือ C++ compiler มีหลายโปรแกรมแบบนี้ แต่เราจะอภิปรายบางตัว

ใน C และ C++ character literals ถูกจัดการต่างกัน ใน C ถือเป็น int แต่ใน C++ ถือเป็น character ดังนั้นถ้าเช็คขนาดด้วย sizeof() จะได้ 4 ใน C และ 1 ใน C++

สำหรับ C:

ตัวอย่าง

#include<stdio.h> int main() { printf("The character: %c, size(%d)", 'a', sizeof('a')); }

ผลลัพธ์ (C)

The character: a, size(4)

สำหรับ C++:

ตัวอย่าง

#include<stdio.h> int main() { printf("The character: %c, size(%d)", 'a', sizeof('a')); }

ผลลัพธ์ (C++)

The character: a, size(1)

ใน C ถ้าใช้ struct ต้องใช้ struct tag ตอนใช้งาน จนกว่าจะใช้ typedef แต่ใน C++ ไม่ต้องใช้ struct tag

สำหรับ C:

ตัวอย่าง

#include<stdio.h> struct MyStruct { int x; char y; }; int main() { struct MyStruct st; st.x = 10; st.y = 'd'; printf("Struct (%d|%c)", st.x, st.y); }

ผลลัพธ์ (C)

Struct (10|d)

สำหรับ C++:

ตัวอย่าง

#include<stdio.h> struct MyStruct { int x; char y; }; int main() { MyStruct st; st.x = 10; st.y = 'd'; printf("Struct (%d|%c)", st.x, st.y); }

ผลลัพธ์ (C++)

Struct (10|d)

ขนาดของ Boolean type ต่างกันใน C และ C++

สำหรับ C:

ตัวอย่าง

#include<stdio.h> int main() { printf("Bool size: %d", sizeof(1 == 1)); }

ผลลัพธ์ (C)

Bool size: 4

สำหรับ C++:

ตัวอย่าง

#include<stdio.h> int main() { printf("Bool size: %d", sizeof(1 == 1)); }

ผลลัพธ์ (C++)

Bool size: 1