[英]Different outputs of sizeof operator in C and C++
C和C ++中sizeof()
運算符的不同輸出。
在C:
int main()
{
printf("%zu\n", sizeof(1 == 1));
return 0;
}
輸出:
4
在C ++中:
int main()
{
std::cout << sizeof(1 == 1) << std::endl;
return 0;
}
輸出:
1
問題:
sizeof
是否獨立於操作系統或編譯器? 6.5.9平等運營商
==
(等於)和!=
(不等於)運算符類似於關系運算符,除了它們的優先級較低。 如果指定的關系為真,則每個運算符產生1
如果為假,則產生0
。 結果是int
類型 。
因此, sizeof(1 == 1)
將返回與sizeof(int)
相等的值,這是實現定義的 ,在您的情況下,它是4
。
5.10平等運營商
==
(等於)和!=
(不等於)運算符組從左到右。 操作數應具有算術,枚舉,指針或指向成員類型的指針,或者鍵入std::nullptr_t
。 運算符==
和!=
都生成true
或false
,即bool
類型的結果 。
因此, sizeof(1 == 1)
將返回與執行定義的 sizeof(bool)
相等的值,在您的情況下為1
。
因為C中的結果類型是int
(並且4個字節是典型大小),而在C ++中它是bool
(並且1是典型的大小)。
這些值取決於實現。
這是一個C11程序,演示了使用_Generic
(典型輸出int 4
):
#include <stdio.h>
void what_int(){
printf("int %lu",sizeof(int));
}
void what_other(){
printf("other ?");
}
#define what(x) _Generic((x), \
int : what_int(),\
default: what_other()\
)
int main(void) {
what(1==1);
return 0;
}
這是一個C ++程序,它演示了使用模板specializaton(典型的輸出bool 1
):
#include <iostream>
template<typename T>
void what(T x){
std::cout<<"other "<<sizeof(T);
}
template<>
void what(bool x){
std::cout<<"bool "<<sizeof(bool);
}
int main(){
what(1==1);
return 0;
}
我不能輕易想到任何同時具有不同結果的C和C ++代碼。 請接受這是一個挑戰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.