Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested function in C

Tags:

c

function

nested

Can we have a nested function in C? What is the use of nested functions? If they exist in C does their implementation differ from compiler to compiler?

like image 524
Sachin Chourasiya Avatar asked Apr 09 '10 14:04

Sachin Chourasiya


People also ask

What is nesting of function give example?

For example, here we define a nested function named square, and call it twice: foo (double a, double b) { double square (double z) { return z * z; } return square (a) + square (b); } The nested function can access all the variables of the containing function that are visible at the point of its definition.

What are nested functions in programming?

In computer programming, a nested function (or nested procedure or subroutine) is a function which is defined within another function, the enclosing function.

What is the meaning of nested function?

Nested (or inner, nested) functions are functions that we define inside other functions to directly access the variables and names defined in the enclosing function. Nested functions have many uses, primarily for creating closures and decorators.

Can you have a function inside a function in C?

No you can't have a nested function in C . The closest you can come is to declare a function inside the definition of another function. The definition of that function has to appear outside of any other function body, though.


2 Answers

You cannot define a function within another function in standard C.

You can declare a function inside of a function, but it's not a nested function.

gcc has a language extension that allows nested functions. They are nonstandard, and as such are entirely compiler-dependent.

like image 195
James McNellis Avatar answered Nov 15 '22 22:11

James McNellis


No, they don't exist in C.

They are used in languages like Pascal for (at least) two reasons:

  1. They allow functional decomposition without polluting namespaces. You can define a single publicly visible function that implements some complex logic by relying one or more nested functions to break the problem into smaller, logical pieces.
  2. They simplify parameter passing in some cases. A nested function has access to all the parameters and some or all of the variables in the scope of the outer function, so the outer function doesn't have to explicitly pass a pile of local state into the nested function.
like image 33
Marcelo Cantos Avatar answered Nov 15 '22 22:11

Marcelo Cantos