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

后端 未结 10 1446
傲寒
傲寒 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 09:57

    If a program declared four variables, one of type int, one of type float, one of type char, and one of type bool, which variable would occupy the least space in memory?

    The real problem with the question your have posted lies in these words:

    occupy ... space in memory

    If an interpretation is to be assumed, then in most occasions you would assume one of the current popular compilers in which case answer 2 and 4 would both occupy the least space in memory. Simply because the current popular compilers make the char and bool occupy a single byte in memory...

    As outlined in the comments, sizeof() is of type size_t, which is integral.

    As sizeof(char) == 1 is always true as per the standard, and the value is integral; no other sizeof(T) can be lower than 1. But any other T than char can be bigger than 1 dependening on the implementation. As you can't assume that sizeof(char) == sizeof(bool) always holds, you can at least assume that sizeof(char) <= sizeof(bool) holds.

    Which makes sizeof(char) being the least the most correct answer...

提交回复
热议问题