Is this a proper C declaration? If so, why is it not working?

I am writing a demo program from a tutorial made to teach "C" for Unix and Windows. However, sometimes I come across code that, when typed for sure, 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; } 

In any case, as I mentioned in the title, I am curious if these variables are correctly declared. I am using Windows (7).

+1
source share
5 answers

There should be no error with the C compiler, because bool is neither a type nor a reserved word in C.

Together with the C ++ compiler, you are likely to get a parsing error.

+1
source

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

+3
source

I think the paint of the code really finds an error for you. Although ANSI C does not have the bool keyword (although C99 saves _Bool as a keyword), most likely the compiler you use extends the standard and defines the bool keyword, especially since it exists in C ++ and other languages ​​related to C. Solution simple: either make the compiler be ANSI compatible, or just change the variable name.

+3
source

Perhaps because bool is a type inside the C ++ compiler, which is a reserved word. So this may depend on which compiler you are using.

0
source

In the future, please indicate the exact error message from the compiler, as well as a description of which development environment you are using (Visual Studio, Eclipse, gcc, tcc, lcc-win, etc.). It will also help you find out which book you are using; non-trivial number of books on programming in C shit .

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

0
source

Source: https://habr.com/ru/post/892757/


All Articles