Why am I getting “error: expected '}'” in C++ but not in C?

前端 未结 3 445
轻奢々
轻奢々 2021-01-21 07:34

I\'m getting \"error: expected \'}\'\" where the \'^\' is pointing when I compile in the following C++ source:

typedef enum { false, true } Boolean;         


        
相关标签:
3条回答
  • 2021-01-21 08:11

    false and true are C++ keywords, so you can't use them as enum identifiers.

    In C they are not keywords so your code will work, but if you include <stdbool.h> then it will fail to compile because that header defines false and true as macros.

    Note that you probably shouldn't implement a boolean type yourself. C++ already has the bool type, and if you are using a C99 compiler, you can include stdbool.h. This will give you a bool type that has false and true values, similar to C++.

    0 讨论(0)
  • 2021-01-21 08:27

    To solve this you need to do:

    #ifdef __cplusplus
      typedef bool Boolean;
    #else
      typedef enum { false, true } Boolean;
    #endif
    

    That way, you are not trying to use C++ keywords (true and false) in an enum.

    0 讨论(0)
  • 2021-01-21 08:29

    The true and false are keywords in C++. You cannot use them in enum identifiers.

    As it is said in the standard :

    2.12 Keywords [lex.key]

    The identifiers shown in Table 4 are reserved for use as keywords (that is, they are unconditionally treated as keywords in phase 7) except in an attribute-token.

    In table 4:

     false
     ...
     true
    

    In C, they are not keywords, your code should work but the best should be to include <stdbool.h> who already defines true and false then you don't need to define them by yourself.

    0 讨论(0)
提交回复
热议问题