A function definition inside another function definition: is it really?

see this code

#include<stdio.h> int main() { void test(void) { printf("test"); return; } printf("main"); return 0; } 

This coed works fine and does not give any warnings and errors. I do not understand why this is happening? here I wrote one function definition inside another function definition, is it really so?

EDIT: if so, is there any use for this?

Why gcc needs to add these functions as an extension .. there should be some use of this, right ?!

+6
source share
5 answers

Attaching function definitions depends on the GCC extension for operation. It is not described by the standard.

If you want your code to work with other compilers, you should refrain from using such methods. What else, if you work with other developers, I predict that many of them will not like the use of such custom designs.

I'm not an expert with GCC, but I'm sure there are compiler options for disabling extensions. This will allow you to get a compiler to make sure that you are not writing code that will not compile with other compilers.


As for your update, nested functions are used. They can help encapsulate, limiting volume and visibility. However, there is no problem that cannot be solved quite adequately without nested functions, which, I think, explain why they are rarely used by the GCC feature.

+6
source

The definition of a nested function (i.e. inside another function) is valid, the only limitation is that the area of ​​the first function is limited by the closing function. This is exactly the same as defining a local variable. You can find more information here: http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

+3
source

Joachim's answer about nested functions that are extensions to GCC is correct; you also asked if there was any use for it: I saw the source code from hundreds of projects and never saw anyone use this particular GCC extension.

+2
source

Yes, we can define a function in another function. I compiled below written lines in gcc and successfully executed without showing errors.

 #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); } 

O / R: 60

+2
source

I know GCC has this extension. This is not, as far as I know, part of the standard.

+1
source

Source: https://habr.com/ru/post/901278/


All Articles