Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mystery with bool data type

Tags:

c

boolean

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

int main()
{
bool a[5]={0,1,0,0,0};
a[1]=3;
printf("\n bool is %d",a[1]);
printf("\n sizeof bool is %d and size of a is %d",sizeof(bool),sizeof(a));

bool b[10];
printf("\n bool is %d",b[1]);

}

output of this program is

 bool is 1
 sizeof bool is 1 and size of a is 5
 bool is 4

Question :

1> bool store 1 bit then why sizeof(bool) is 1 byte ?

2> if bool has 1 byte then when i assign a[1] = 3 then why it print 1 ?

3> if bool only consider 1 & o value to be store then why b[1] prints value 3 ?

like image 243
Jeegar Patel Avatar asked May 01 '26 09:05

Jeegar Patel


2 Answers

1> Bool store is not 1 bit. Nothing is 1 bit. Everything is at least 1 byte. sizeof(bool) is platform specific. Only sizeof(char) is guaranteed to be 1.

2> It implicitly converts int to bool : (bool)3 == 1

3> the array b is not initialized, it can have any value. You're just accessing some memory.

like image 64
Luchian Grigore Avatar answered May 03 '26 00:05

Luchian Grigore


The reason the last printf prints a 4, is because the b array is not initialized, which means the printf-function just takes whatever value is already in the memory.

like image 21
Some programmer dude Avatar answered May 02 '26 23:05

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!