size of a datatype without using sizeof

后端 未结 21 1965
慢半拍i
慢半拍i 2020-12-01 02:34

I have a data type, say X, and I want to know its size without declaring a variable or pointer of that type and of course without using sizeof oper

21条回答
  •  渐次进展
    2020-12-01 02:53

    This takes into account that a C++ byte is not always 8 binary bits, and that only unsigned types have well defined overflow behaviour.

    #include 
    int main () {
        unsigned int i = 1;
        unsigned int int_bits = 0;
        while (i!=0) {
            i <<= 1;
            ++int_bits;
        }
    
        unsigned char uc = 1;
        unsigned int char_bits = 0;
        while (uc!=0) {
            uc <<= 1;
            ++char_bits;
        }
    
        std::cout << "Type int has " << int_bits << "bits.\n";
        std::cout << "This would be  " << int_bits/8 << " IT bytes and "
                  << int_bits/char_bits << " C++ bytes on your platform.\n";
        std::cout << "Anyways, not all bits might be usable by you. Hah.\n";
    }
    

    Surely, you could also just #include or .

提交回复
热议问题