Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Function declare in function

Tags:

c++

Why does this compile?

int main() {
    void f();
}

What is f? Is it a function or a variable and how can I use it?

like image 762
avalanche Avatar asked Sep 27 '13 18:09

avalanche


People also ask

Can I declare a function inside a function in C?

Nested function is not supported by C because we cannot define a function within another function in C.

Can I define a function inside a function?

A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation .

Can we declare variable in function in C?

Variable Declaration in C You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.

How do you declare a function in the main 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 ...


1 Answers

You have a function declaration. It's OK to declare functions inside a block scope. It's just not possible to define a function in a block. Declaring a function only locally is perfectly fine, e.g. when you want to refer to some other, existing function:

int main()
{
    int foo();
    return foo();
}

You just have to link this with some translation unit that defines int foo();.

(It's probably just not very good practice to do this, since it hides the dependency of your code on the other function in a way that's almost impossible to see without careful reading of the code.)

Note that the local declaration hides other overloads of the function, so argument lookup may be dif­fer­ent from if you had declared the function at the global scope. See @David Rodríguez's vastly more de­tailed answer.

like image 109
Kerrek SB Avatar answered Nov 03 '22 22:11

Kerrek SB