Syntax: Single statement in function declaration
In the C programming language, it is possible to omit a code block in the case of a single statement, for example:
if(1) exit();开发者_开发技巧
Now, does this only apply to conditionals ? Why is this not valid in the case of functions:
void f(int a) exit();
It's a feature of C syntax. In BNF, a function definition is something like
FUNC_DEF ::= TYPE IDENTIFIER "(" PARAM_LIST ")" BLOCK
while a statement is
STATEMENT ::= (EXPRESSION | DECLARATION | CONTROL | ) ";" | BLOCK
BLOCK ::= "{" STATEMENT* "}"
(simplifying to allow intermixed declarations and statements, which C++ allows but C doesn't), and an if
statement is
CONDITIONAL ::= "if" "(" EXPRESSION ")" STATEMENT
omitting the else
part for now.
The reason for this is that otherwise, you could write the function
void no_op() {}
as
void no_op();
but the latter syntax is already in use to denote a declaration.
The syntax of a conditional statement is this:
if(expression) statement
A compound statement is a statement.
A
compound statement
is defined as{ zero or more statements }
The syntax of a function definition is this
function_declaration compound_statement
So, by definition a function body must be a compound statement and have
{}
QED :)
There is a very old dialect of C, the K&R C. In this dialect the function declaration may look like this:
fun_a(a,b)
char a;
float b;
{
fun_b(b,a);
}
I think it would be too hard to parse it without {
and }
.
精彩评论