Of int, char, float, and bool, which is smallest?

后端 未结 10 1444
傲寒
傲寒 2021-02-02 09:51

The following is from a \"fill-in at home\" programming test that is part of the application process for an MSc in game development at a UK university:

C+

10条回答
  •  不要未来只要你来
    2021-02-02 10:12

    The answer is char. No other answer is correct.

    (Though I agree the question should have been worded better).

    The C++03 Standard $5.3.3/1 says:

    sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined. [Note: in particular, sizeof(bool) and sizeof(wchar_t) are implementation-defined.69)

    (Found this info from another question: Why the sizeof(bool) is not defined to be one, by the Standard itself?).

    Given that the minimum size is 1 (sizeof must return integral values), this means that the following will be true in any implementation that follows the standards:

    sizeof(char) == 1
    sizeof(bool) >= 1
    sizeof(int) >= 1
    sizeof(float) >= 1
    

    The question was poorly phrased and probably should have been asked more clearly as "...which variable would necessarily occupy no more space in memory than any other (in any well-behaved standard implementation of C++)?"

提交回复
热议问题