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?
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.
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 ...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With