代码之家  ›  专栏  ›  技术社区  ›  msc

C和C中sizeof算子的不同输出++

  •  5
  • msc  · 技术社区  · 7 年前

    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
    • 它取决于语言吗?
    3 回复  |  直到 6 年前
        1
  •  18
  •   Akira    7 年前

    根据 N1570 ):

    6.5.9等式运算符

    这个 == (等于)和 != 1 如果指定的关系为true,并且 0 如果为假。 int .

    因此 sizeof(1 == 1) 将返回相等的值 sizeof(int) 这就是 定义的实现 4 .


    根据 N4296 ):

    这个 == (等于)和 (不等于)运算符组从左到右。操作数应具有算术、枚举、指针或指向成员的指针类型或类型 std::nullptr_t .运营商 != true false ,即。, bool .

    因此 将返回相等的值 sizeof(bool) 定义的实现 1. .

        2
  •  15
  •   kocica    7 年前

    C 的结果 == != 操作员是 int

    根据 N1570 草稿- 6.5.9等式运算符

    4 sizeof(int)


    在里面 C++ 的结果 == 操作员是 bool

    根据 N4296 草稿-

    1 方法 sizeof(bool) 大小不能小于一个字节。但大于一个字节是合法的。

        3
  •  7
  •   Persixty    7 年前

    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++程序,它演示了使用模板专门化(典型输出 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++的代码会有不同的结果。请接受这一挑战。