程式碼在 C 和 C++ 中都是有效的,但會產生不同的輸出


此處我們將看到一些程式,如果在 C 或 C++ 編譯器中編譯,它們將返回不同的結果。我們可以找到許多此類程式,但此處我們將討論其中的部分程式。

  • 在 C 和 C++ 中,字元字面量有不同的處理方式。在 C 中,它們被視為 int,而在 C++ 中,它們被視為字元。因此,如果我們使用 sizeof() 運算子檢查大小,它將在 C 中返回 4,在 C++ 中返回 1。

示例

 線上演示

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

輸出

The character: a, size(4)

示例

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

輸出 (C++)

The character: a, size(1)

在 C 中,如果我們使用結構,那麼必須在使用它時使用結構標記,直到使用某種型別定義。但在 C++ 中,我們無需使用結構標記來使用結構。

示例

 線上演示

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

輸出 (C)

Struct (10|d)

示例

 線上演示

#include<iostream>
struct MyStruct{
   int x;
   char y;
};
int main() {
   MyStruct st; //struct tag is not present
   st.x = 10;
   st.y = 'd';
   printf("Struct (%d|%c)", st.x, st.y);
}

輸出 (C++)

Struct (10|d)

布林型資料的大小在 C 和 C++ 中是不同的。

示例

 線上演示

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

輸出 (C)

Bool size: 4

示例

 線上演示

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

輸出 (C++)

Bool size: 1

更新日期:17-Dec-2019

67 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.