I've tried to compile a code using a bool variable in C and I've included the stdbool header but when I compiled it I didn't specify that I want to compile it with the c99 standard (so it was compiled with ANSI C standard) but it worked anyway. I was wondering why is that ? Here's the code :
#include <stdio.h>
#include <stdbool.h>
int main() {
char name[20];
printf("What's your name ? ");
gets(name);
printf("Nice to meet you %s.\n", name);
bool exit = false;
char c;
printf("Do you wish to exit the program ? (Y/N) ");
while (!exit) {
c = getchar();
if (c == '\n') {
continue;
}
printf("Do you wish to exit the program ? (Y/N) ");
if (c == 'Y' || c == 'y') {
exit = true;
}
}
printf("Have a nice day %s\n", name);
return 0;
}
Also another question regarding to my code. In the part where you are being asked if you wish to exit the program, I've tested it with the following input : n n y
And for some reason it printed out to the console the question for the fourth time and I don't see why. I've set it so if the input is Y/y the next iteration in the while loop shouldn't take place but for some reason it printed it again, could someone explain me what I did wrong ?
EDIT : So I've edited the code a bit tried to test new things and I've noticed that with the following code if the user input is Y/y it won't come out of the loop :
#include <stdio.h>
#include <stdbool.h>
int main(int argc, char* argv[]) {
for(int i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
char name[20];
printf("What's your name ? ");
gets(name);
char lastname[20];
printf("%s what's your last name ? ", name);
fgets(lastname, 20, stdin);
int age;
printf("%s %s what's your age? ", name, lastname);
scanf("%d", &age);
bool exit = false;
char c;
while (!exit) {
printf("Do you wish to exit the program ? (Y/N) ");
c = getchar();
getchar();
if (c == 'Y' || c == 'y')
exit = true;
}
printf("Have a nice day %s %s.\n", name, lastname);
return 0;
}
I don't know why I did it but I added a getchar() call before the while loop and tried to compile it this way and then the program worked fine, from this I assume that the fgets\scanf functions interfering with the getchar function but I'm not sure why could someone explain ?
Most C compilers extend the base language with extensions. One such extension could be to let the stdbool.h
work even in C90 mode. If you really want to, you can usually turn off most of the extensions with some compiler flag, e.g. for gcc use -std=c90
. Not sure about extra headers, the file is still there after all, so it can probably be included regardless of mode.
For your second question, try stepping through the program, printing the value of c
at each step. It should make it fairly obvious what's happening.