I expect the following code to compile. Clang and VC++ both give me an error on the line with else
.
void MyFunction(std::int32_t& error) { std::int32_t variable = 0; if(GetSomething()) error = EOK; else error = ERROR; }
If I put curly braces around error = EOK;
, then it compiles. Why does VC++ say:
illegal else without matching if
?
My full code is below, replacing std::uint32_t with a typedef. It still gives the same error in VC++.
using sint32 = int; #define ERROR 5; #define EOK 0; bool GetSomething(); void MyFunction(sint32& error) { sint32 variable = 0; if (GetSomething()) error = EOK; else error = ERROR; }
If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.
One-line statement Well if there is only one statement to execute after if condition then using curly braces or not doesn't make it different. Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces.
If the single statement looks good on a single line after the if clause, I don't use braces. For any other if statement (or any statement that uses multiple lines), I always use braces. In particular, if there's an else clause, each case always has braces.
For Java, curly braces are optional for if-else statements. As Jared stated, only the next statement will be executed when curly braces are omitted. Generally the braces help with organization and readability of the code, so they commonly will be used.
If your definition of EOK is as follows:
#define EOK 0;
then it would cause this type of error, because it forcibly terminates the if-statement before the else is reached, making it an else without a matching if. The compiler sees this code after macro replacement:
if(GetSomething()) error = 0;; else
Here is a possible fix:
enum { EOK = 0, ERROR = 5 };
Note that all identifiers starting with E
followed by either another uppercase letter or a number are reserved for use as macro names by <cerrno>
, so to avoid name clashes consider using a different naming convention for your errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With