开发者

Is this proper C declaration? If so, why does it not work?

开发者 https://www.devze.com 2023-03-20 19:18 出处:网络
I\'m writing a demo progra开发者_StackOverflow社区m from an educational book made to teach \"C\" for Unix and Windows. However, sometimes I come across code that, when typed exactly, does not want to

I'm writing a demo progra开发者_StackOverflow社区m from an educational book made to teach "C" for Unix and Windows. However, sometimes I come across code that, when typed exactly, does not want to work.

Eg.

#include <stdio.h>

int main()

{
    /*This next line is the error */

    int num = 2, bool = 0;

    if ( (num==2) && (!bool) )
    {
         printf("The first test is untrue\n");
    }
    else if( (num==2) && (!bool) )
    {
         printf("The second test is true\n");
    }
    else if( (num==2) && (bool==0) )
    {
         printf("The third test is true - but unreached\n");
    }
    return 0;
}

Anyway, like I mentioned in the title, I am curious if I have these variables declared properly. I am using a windows OS (7).


I think Stack Overflow's code coloring actually finds the error for you. Although ANSI C has no bool keyword (although C99 does reserve _Bool as a keyword), most likely the compiler you're using extends the standard and does define a bool keyword, especially since it does exist in C++ and other C derived languages. The solution is simple: either force your compier to be ANSI compliant or just change the variable name.


bool is now a reserved word in C++ and can't be used as a name of a variable. When the book was written, bool was not a reserved word in C and they used it as the name of an int variable.


With a C compiler, there shouldn't be an error because bool is neither a type nor a reserved word in C.

With a C++ compiler, however, you will probably get a parsing error.


In the future, please include the exact error message from the compiler, along with a description of what development environment you're using (Visual Studio, Eclipse, gcc, tcc, lcc-win, etc.). It would also help to know which book you're using; a non-trivial number of books on C programming are crap.

My suspicion is that you're somehow compiling the code as C++, not C, and bool is a reserved word in C++. If you're using Visual Studio, make sure the filename extension is .c, and not .cpp.


Perhaps because bool is a type within a C++ compiler, which is a reserved word. So, it may depend upon what compiler you are using.

0

精彩评论

暂无评论...
验证码 换一张
取 消