Reputation: 51
I have been driving myself crazy trying to figure out why the first if statement (if hungry is true or false) will not display the appropriate response. IF you hit true or false it just wont print the statement. I feel like its a silly obvious mistake... but I cant spot it. ----EDIT----
It will not show anything for the first condition/if statement (hungry) If you put in 1 or 0, it wont display the prinft statement to go along with it.
#include<stdio.h>
#include<stdbool.h>
int main (void){
_Bool hungry = 0;
_Bool thirsty = 0;
_Bool sleepy = 0;
printf("Are you hungry? (1 - true 0 - false) : ");
scanf("%d", &hungry);
printf("Are you thirsty?: ");
scanf("%d", &thirsty);
printf("Are you sleepy?: ");
scanf("%d", &sleepy);
if ( hungry ) {
printf("Ordering manty \n");
}
if ( thirsty ) {
printf("Ordering pot of hot tea \n");
}
else {
printf("Ordering cup of water \n");
}
if ( sleepy ) {
printf("Ordering black coffee \n");
}
else {
printf("Ordering baursaki \n");
}
}
Upvotes: 0
Views: 497
Reputation: 64682
The sizeof(_Bool)
is 1, or 1-byte.
By trying to scanf-%d
into it, you are trying to put 4-bytes into a space only big enough for one byte. From that point on, you have undefined behavior.
I'd recommend:
int temp; // Temp is 4-bytes. (assuming 32-bit system)
scanf("%d", &temp); // %d matches 4-byte int.
hungry = !!temp; // !! converts int value into _Bool value.
Upvotes: 1
Reputation: 141554
This code causes undefined behaviour:
_Bool hungry = 0;
scanf("%d", &hungry);
The %d
format specifier requires argument of type int *
, but you supplied _Bool *
. The printf and scanf family do not do any type conversions -- it is up to the programmer to make sure the correct argument type is supplied.
In fact there is no format specifier for _Bool
. You have to read into another variable and then assign to the bool, e.g.:
int temp = 0;
scanf("%d", &temp);
hungry = temp;
You might like to check the return value of scanf
, and perhaps also check temp
and take action if the input was unexpected.
Upvotes: 2