Compile error in if statement without braces

This topic is 2067 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I get an error stating that a ';' is expected after the if statement when I try to compile the following code.

if( true )
MyHandle @handle = cast<MyHandle>(object.getMyHandle("MyHandleName"));


However if I change the code like this, the error goes away.

MyHandle @handle;
if( true )
@handle = cast<MyHandle>(object.getMyHandle("MyHandleName"));


The error also goes away if I change the code like this.

if( true )
{
MyHandle @handle = cast<MyHandle>(object.getMyHandle("MyHandleName"));
}


Is this maybe a bug in the compiler??

Share on other sites

It's not a bug. This was a conscious decision on my part.

The thing is that the variable that is declared would only live for that single statement, which makes it useless. It is also a quite common bug in C++ where developers mistakedly declare variables like this and then discover (possibly after long hours of debugging) that the value is not visible in the following statements (especially if the variable happen to have the same name as another variable declared at a higher scope).

The error message could be clearer though. It should be something like 'Cannot declare variable as the only result of condition'.

Share on other sites

Thanks for the response. I agree that it is a totally pointless statement and would never actually do it myself, but I just stumbled across it while putting AngelScript through its paces and wasn't sure if it was intentional or a bug. I think it would be a great idea to use clearer messages when you've intentionally deviated away from something that would otherwise compile in c++ for example. Cheers for the prompt support too

• Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 16
• 11
• 23
• 42
• 75