Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if and else without braces

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; } 
like image 992
Graznarak Avatar asked Oct 06 '14 19:10

Graznarak


People also ask

Do if else statements need braces?

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.

What happens if you omit the curly braces in an if and else or an ELSE IF statement?

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.

Does else need brackets in C?

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.

Does else need curly 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.


2 Answers

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 
like image 70
T.W.R. Cole Avatar answered Sep 25 '22 05:09

T.W.R. Cole


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.

like image 29
M.M Avatar answered Sep 26 '22 05:09

M.M