Difference in output for sizeof operator for boolean values in C and C++

Viewed 142
#include<stdio.h>
#include<stdbool.h>
int main()
{
    printf("%d",sizeof(true));
    printf("%d",sizeof(false));
}

The output of the above code in C++ is 11 and in C is 44. Why is there a difference in the output?

3 Answers

In C, true and false are macros defined in <stdbool.h> that expand to the integer constants 1 and 0, which have type int, per C 2018 7.18 3. The size of int is implementation-defined, and 4 is a common size.

In C++, true and false are literals with bool type, per C++ 2017 draft n4659 5.13.6 1. The size of the bool type is implementation-defined, per C++ 8.3.3 1, so you may get 1 for it, which is common in C++ implementations.

(Use %zu to print sizes obtained with sizeof, not %d.)

true and false have different meanings in C vs C++.

In C, my copy of stdbool.h defines true and false as follows:

#define true         1
#define false        0

That is, they are both macros for the literals 1 and 0, respectively. In C, numeric literals default to the type int, which on most systems is 4 bytes. Hence, we have sizeof(true) == sizeof(false) == sizeof(int), which on your system is 4.

In contrast, C++ includes a distinctive boolean type. While not required by the standard, most implementations provide bools that occupy only one byte. This is the case on your system, hence sizeof(bool) == 1.

While the C standard does not require the cpp part of the header still if you look at widely used compilers like GCC implementation of the stdbool.h (Clang's one similar) file you see

#ifndef _STDBOOL_H
#define _STDBOOL_H

#ifndef __cplusplus

#define bool        _Bool
#define true        1
#define false        0

#else /* __cplusplus */

/* Supporting <stdbool.h> in C++ is a GCC extension.  */
#define _Bool        bool
#define bool        bool
#define false        false
#define true        true

#endif /* __cplusplus */

/* Signal that all the definitions are present.  */
#define __bool_true_false_are_defined        1

#endif        /* stdbool.h */

In C case true and false are essentially integer literals so you will get the sizeof(int). But in C++ case virtually nothing happen with this header so you will get the sizeof(bool) which is usually 1, but it is implementation defined actually.

If you would do this in C++ then you would get similar result like in C.

#include<stdio.h>
#include<stdbool.h>

#define true 1
#define false 0

int main()
{
    printf("%zu",sizeof(true));
    printf("%zu",sizeof(false));
}
Related