Student
Student

Reputation: 719

Declaring function prototypes locally in other functions in C

What is the point of making nested function? This happens in the book of K&R "The C Programming Language" sometimes, e.g. on page 110 they declare a swap function in the qsort:

void qsort(char *v[], int left, int right)
{
   int i, last;
   void swap(char *v[], int i, int j);
   etc.

Is this only a matter of style or is there a more crucial aspect behind it?

Upvotes: 1

Views: 131

Answers (1)

Yun
Yun

Reputation: 3812

It limits the visibility of the declared function to that function.

For example, if we have a file hw.c which contains

#include <stdio.h>

void printHelloWorld()
{
    printf("Hello world\n");
}

and a file main.c which contains

void func()
{
    // printHelloWorld(); // Incorrect, function is not visible here.
}

int main()
{
    void printHelloWorld();
    printHelloWorld();

    func();
}

then the function printHelloWorld is only visible to the main function for that file.

A similar, although less useful, application is when the two functions are in the same file. Let's say main is defined first (as above) and printHelloWorld is defined below it. Then printHelloWorld will be visible from it definition downwards, with the exception of it also being visible in main.

That said, this method of declaring functions is rare and I would not call it idiomatic C.

Upvotes: 1

Related Questions