Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

c++ - 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;
}
question from:https://stackoverflow.com/questions/26223907/if-and-else-without-braces

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...