Jack
Jack

Reputation: 16724

Functions inside functions

if I do:

void foo() {
    if( .. ) {
      inline int baa(..) { return .. }
    } else {
      inline int baa(..) { return .. }
    }

}

And call: baa(..) inside foo function I get implicit declaration of 'baa'. But if I do prototype declaration: inline int baa(int); the error is inline function 'baa' declared but never defined. I'm using inline function to replace macro-function.

How to fix this?

EDIT better: can someone explain why the compiler claims the above error message?

Upvotes: 0

Views: 156

Answers (3)

ugoren
ugoren

Reputation: 16441

K-ballo's suggestion indeed seems best, but he didn't actually point out the problem.

A nested function, defined in a block, is valid only within the block. Just like a normal variable. You define one function in the if clause, and another in the else clause, and each is valid within that clause. But neither is valid after the if-else has been closed.

It's exactly the same with variables:

if (a) {
    int x = 3;
} else {
    int x = 4;
}
// x isn't valid here.

Upvotes: 1

eqzx
eqzx

Reputation: 5569

Although it's not part of the standard, you could compile with the flag -fnested-functions

Upvotes: 1

K-ballo
K-ballo

Reputation: 81349

I'm using inline function to replace macro-function.

You cannot define functions inside functions, you can only declare them. Declaring them makes their names visible in that scope but those functions still need a definition somewhere, and we know we cannot define them within another function. That's why the compiler says that the function was declared but never defined.

Instead, simply declare your functions inline at a global scope.

Upvotes: 4

Related Questions