Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax: Single statement in function declaration

Tags:

c

syntax

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();
like image 981
overscore Avatar asked Jul 07 '11 14:07

overscore


People also ask

What is the syntax of function declaration?

Syntax. function name(param0) { statements } function name(param0, param1) { statements } function name(param0, param1, /* … , */ paramN) { statements } name. The function name.

What is the correct syntax for a function with arguments?

When one piece of code invokes or calls a function, it is done by the following syntax: variable = function_name ( args, ...); The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function.

What is a single statement in C?

The single if statement in C language is used to execute the code if a condition is true. It is also called a one-way selection statement.

What is function declaration example?

The first declares a function f that takes two integer arguments and has a return type of void : void f(int, int); This fragment declares a pointer p1 to a function that takes a pointer to a constant character and returns an integer: int (*p1) (const char*);


1 Answers

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.

like image 106
Fred Foo Avatar answered Nov 09 '22 21:11

Fred Foo