views:

95

answers:

2

A quick, fun question - What is the difference between a function declaration in C/C++ and an else-if statement block from a purely parsing standpoint?

void function_name(arguments) {
  [statement-block]
}

else if(arguments) {
  [statement-block]
}

Looking for the best solution! =)

Edit: Thanks for the insight guys. I was actually writing a regex to match all functions in a program and I started getting these else-if blocks with the results. That is when I realized the unique connection between the two. =)

+3  A: 

That what keywords - namely else and if - are reserved for.

Function declarations start with a type and therefore the parser has to make sure there will never be a type-expression like else or if.

Dario
+2  A: 

The two are actually completely different.

A function follows the pattern:

return-type function([argument1, argument2... argumentN]) // arguments optional
{
    [statement-block]
}

An else-if on the other hand, the way you've written it in C style, is a special case of a single statement else block. Just like you can have one statement under an else when the curly braces are omitted:

if (boolean-condition)
    // ...
else
    single-statement;

The single statement is also allowed to be an if-else statement:

if (boolean-condition)
    // ...
else
    if (boolean-condition)
    {
        // ...
    }

more usually written the way you have (else if (...)).

Further, there is no parameter list, just a required boolean condition, and there is no return type in an else if. So one's the definition of a subroutine, and the other is two conditional blocks chained together - there is nothing in particular connecting the two. This is a good example why regex can't be used to parse C++/HTML/XML/anything with complex grammar.

AshleysBrain