Is semicolon really needed after declarations in x++?
You only need the semicolon if the body of your code doesn't start with a keyword. In your example, your code starts with print
, which is a built in keyword. If you had tried to start you code with: string1+=".COM";
you would receive an error.
Dynamics AX 2009 is the last version of AX that will require the extra semicolon. AX 6.0 should fix this: mfp's two cents: What's up with this semicolon?
You really don't need the lovely semicolon (you don't get a compilation error) when the next word after declarations (if any) is not some keyword recognized by compilator like a type (an EDT, table, class, ...)
For example:
void method1()
{
CustTable custTable;
custTable = CustTable::find("cust");
}
ERROR! as compiler can't separate the class declaration block of the start of the X++ code. When compilator reads the second line it doesn't know if custTable is a new variable or is part of the X++ code. So that, you need the extra semicolon to say the compiler where is the end of declarations (really, where is the start of X++ code).
void method1()
{
CustTable custTable;
if (custTable)
{
// stuff happens
}
}
WORKS! as compiler knows that you can't declare a variable of type if
(it's a reserved keyword, obviously) so it's clear that this is the beginning of X++ code and you can't declare variables after this line.
This works that way even if there is no variable declarations:
CustTable method1()
{
custTable = CustTable::find("cust"); // custTable may exists in the context
return custTable;
}
ERROR! custTable
may be a decaration, or X++ code like that example.
CustTable method1()
{
return CustTable::find("cust");
}
WORKS! as return
can't be a declaration.
EXTRA:
void method1()
{
info("This should work, ya?");
}
This should work (as info
is not a type), isn't it? ... but it doesn't! Why? Because info
is an special kernel method that will be replaced to its full name: Global::info()
, first token will be Global
after the precompiler replacement, and Global
is a class.
It's explained rather elegantly here.
A key quote [emphasis mine]:
"The reason you need that extra semicolon is because the compiler can’t always see where the variable declarations end. If you don’t help a little, it will make a guess. And it’s not very good at guessing."
While the compiler is analyzing the code it checks if the first word on a line matches the name of a type (AOT object). If it’s a type name the compiler treats the line as a variable declaration. In this case a variable name should be next.
With the release of AX 2012 there is no need to put the additional semicolon after variable declaration.
http://msdn.microsoft.com/en-us/library/aa636895.aspx