Compiling c code with bool without using c99 standard

拟墨画扇 提交于 2019-12-02 10:19:16

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.

About second question:

Your code deciding to leave program or not is strange, it can be done simpler way:

int c=0;
do{
    if(c!='\n')
        puts("Do you wish to exit the program? (Y/N) ");
    c=getchar();
}while(c!='y' && c!='Y');

When code is simpler, it's harder to make mistake in it.

stdbool.h defines bool, true, and false for you - the header itself is not dependent on the language standard you pass in, so long as you have the header on your system. EDIT - this may only be the case for the stock osx header. gcc's header (4.8) doesn't look like it will work.

Your logic for exiting the loop doesn't look like how you describe what you want it to do. You're still testing the previous character in your y/Y section, even though you printed out the question again at that point. I suggest stepping through your code with a debugger - this will make it more clear to you what's going on. The debugger will be an incredibly important learning tool for you, now and forever. :)

You probably want something like this for your code (remove the first printf question in your code):

while (!exit) {
    printf("Do you wish to exit the program ? (Y/N) ");
    c = getchar();
    if (c == '\n') {
        continue;
    }
    if (c == 'Y' || c == 'y') {
        exit = true;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!