Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Void function call as expressions

Tags:

c

It's clear from the C standard that general function calls are expressions from the definition:

An expression is a sequence of operators and operands that specifies computation of a value, or that designates an object or a function, or that generates side effects, or that performs a combination thereof. The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. (6.5.1)

Since the () are operators and it returns a value, regular function calls are obviously expressions.

But those which don't return a value don't seem to fit with this definition. The function name itself does (as it designates a function), but this isn't a function call.

The standard does clearly say that a function call is an expression, and that it can return void, but this seems to conflict with the definition of an expression. What am I missing?

like image 581
teppic Avatar asked Dec 14 '22 11:12

teppic


1 Answers

Calling a function is an expression regardless of the function's return type. C's grammar is orthogonal to its type system. They are independent pieces of the language. Grammatically func(); is an expression statement.

expression_statement
    : ';'
    | expression ';'
    ;

postfix_expression
    : primary_expression
    | postfix_expression '[' expression ']'
    | postfix_expression '(' ')'
    | postfix_expression '(' argument_expression_list ')'

There are very few things you can do with a void result. You can't assign it to a variable since void variables aren't allowed. If func()'s result is void you can use four operators:

  • Parentheses: (func())
  • Comma sequencing: func(), 42
  • Ternary operator: 42 ? func() : func().
  • Cast to void: (void) func()

You can also return a void result:

return func();

Finally, in a for(init; condition; increment) loop the three pieces are all expressions. init and increment (but not condition) can be void.

for (func(); 42; func()) { }

Few of these are useful and none are good style, but they're all legal.

like image 133
John Kugelman Avatar answered Dec 24 '22 17:12

John Kugelman