Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a use for function declarations inside functions?

Tags:

c++

c

declaration

We can declare functions inside functions (I wanted a local variable, but it parses as a function declaration):

struct bvalue;
struct bdict {
    bdict(bvalue);
}
struct bvalue {
    explict operator bdict() const;
}
struct metainfo {
    metainfo(bdict);
}
void foo(bvalue v) {
    metainfo mi(bdict(v)); // parses as function declaration
    metainfo mi = bdict(v); // workaround
                            // (this workaround doesn't work in the presence of explicit ctors)
}

Are the sole reasons "because it makes the parser simpler" and "because the standard says so", or is there an obscure use for this?

like image 286
R. Martinho Fernandes Avatar asked May 22 '11 17:05

R. Martinho Fernandes


People also ask

Can you declare functions inside functions?

We can declare a function inside a function, but it's not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module.

Can we declare a function inside or outside any function?

The declaration of a user-defined function inside the main() function and outside main() is similar to the declaration of local and global variables, i.e. When we declare a function inside the main, it is in local scope to main() and that function can be used in main() and any function outside main() can't access the ...

Where do declarations go in a function?

A simple declaration can appear wherever a statement can be used. You can declare an object, a type, or a namespace alias. You can also write a using declaration or using directive. You can declare a function, but not define a function, although there is rarely any reason to declare a function locally.

Are function declarations necessary?

Function declarations are mandatory in C. Prototypes, however, are optional, except in the cases of variadic functions and functions whose argument types would be altered by default promotions. Save this answer.


1 Answers

This is really a C question, because this behaviour was inherited directly from C (although it gets much more press in C++ because of the most vexing parse).

I suspect the answer (in the context of C, at least) is that this allows you to scope the existence of your function declarations to precisely where they're needed. Maybe that was useful in the early days of C. I doubt anyone does that any more, but for the sake of backward compatibility it can't be removed from the language.

like image 179
Oliver Charlesworth Avatar answered Sep 20 '22 15:09

Oliver Charlesworth