I intended to call a private class member function, but by a copy&paste mistake pasted the line as this function is declared in the header file:
void DebugView::on_cbYAxisEnabled_stateChanged(int) { void updateAxisEnabled(); }
instead of
void DebugView::on_cbYAxisEnabled_stateChanged(int) { updateAxisEnabled(); }
Surprisingly, the code was compiled and executed. However the method updateAxisEnabled()
was not executed.
So, why does it compile? Was here a local function declared within a method body or has void
instructed the compiler to ignore whatever comes afterwards?
The compiler is Visual Studio 2008.
P.S.: I'm aware of class declaration/definition within functions, but not functions within functions in C++.
A function declaration introduces an identifier that designates a function and, optionally, specifies the types of the function parameters (the prototype). Function declarations (unlike definitions) may appear at block scope as well as file scope.
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 reason modern compilers give warnings on an attempt to call a function before seeing a declaration is that a declaration allows the compiler to check if arguments are of the expected type.
Yes we can define a function in other function. I have compiled below written lines in gcc and it ran successfully without showing an error. #include<stdio.h>; void main() { int sum() { int a=30, b=10, c=20, sum=0; sum=a+b+c; return sum; } int a; a=sum(); printf("Sum = %d", a); }
void updateAxisEnabled();
is a function declaration.
Sample:
#include <cstdio> void a(); void b(); int main(void) { a(); b(); return 0; } void a() { void c(); // Declaration c(); // Call it } void b() { c(); // Error: not declared } void c() { puts("Hello, world!"); }
It is perfectly allowed to declare a function inside a function scope: a function may be declared in any scope.
A common mistake among C++ programmers is indeed to:
void foo() { MyObject bar(); // 1 bar.someMethod(); // 2 }
this will miserably fail to compile because line 1 is not declaring a MyObject
named bar
and calling its constructor explicitly; rather, it is declaring a function named bar
that returns a MyObject
. Thefore, there is really no object to call someMethod
on.
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