I have been writing quite a bit of C code for the past few months, I never really thought that it was that different from C++. Boy, was I wrong. There are many differences, and in some sense, I found C a lot more fun.
One of the differences that had me really surprised is the lack of a boolean data type. Prior to the 1999 standard of C (C99), The C programming language didn’t have a boolean data type. The reason for that is because they didn’t specifically need it. They just used good ol’ integers or characters, basically anything that can be used with value 0 for false and any other value for true. In the end, everything is stored as bytes in memory. (Check the bonus at the end of the article)
_Bool keyword was added in 1999 to refer to the boolean data type, which looks kinda ugly. So, they also added the stdbool.h header file which just had macros so that you can use the keyword
If you didn’t include it, you’d have to use
_Bool for a boolean,
Part of the stdbool.h header (C99)
This is just a quick fact that you might not have known, and I found it interesting. If you liked it then share it with your friends! If you want to read more then check the bonus part of the article, it’s a little bit more technical and even has some assembly code in it.
Earlier in this post, I said that everything is stored as bytes in memory, that means that the CPU doesn’t care whether you typed
bool in your code as they both occupy 1 byte.
If you typed in
int, however, that would be quite different. Depending on your platform, an integer may occupy 4 or more bytes. It can also occupy 2, but that’s with really old 16-bit platforms.
I did a small test on a 64-Bit Linux machine running on an Intel i5 2400 with GCC 8.3.0.
The 3 files were compiled and their respective binaries were disassembled. That’s what we got, respectively.
char.c and bool.c both compiled to the same machine instructions, here they are simplified:
- Allocate a byte (For a char/bool)*
- Move the value 1 into that byte.
- Return 0.
int.c compiled to slightly different machine instructions.
- Allocate a double word (4 bytes for an integer)*
- Move the value 1 into those 4 bytes.
- Return 0.
*Note that if the file was compiled on a different platform, the size of the integer, and maybe other data types may vary.
Thanks for reading!