Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a function inside a function?

Tags:

c

I have came across the following code, and being a C beginner, I came here for your help.

This function is from a c implmentation of a queue.

Bool queuePut(Queue *q, char c) 
{
    void beep();

    if (queueFull(q)) 
    {
        beep();
        return false;
    }

    //do stuff

    return true;
}

So, I am getting a strange error with gcc on the void beep(). Can someone please explain me what is this, declaring a function inside a function. Or is it the void beep() simply out of place? I was given this code and there's always the possibility that it isn't correct.

Edit: The error I am getting:

c:/djgpp/tmp/src/ccrjtmBh.o:queue.c:(.text+0x50): undefined reference to
    '_beep'
collect 2: ld returned 1 exit status.

Is this a linking error?

like image 476
nunos Avatar asked Mar 20 '10 19:03

nunos


People also ask

Can I declare a function inside a function?

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.

Can you declare a function inside a function in JavaScript?

Nested functions A function is called “nested” when it is created inside another function. It is easily possible to do this with JavaScript. Here the nested function getFullName() is made for convenience. It can access the outer variables and so can return the full name.

Can I define a function inside a function in C++?

No, it's not allowed. Neither C nor C++ support this feature by default, however TonyK points out (in the comments) that there are extensions to the GNU C compiler that enable this behavior in C.

Can you put a function inside a function in Excel?

The AVERAGE and SUM functions are nested within the IF function. You can nest up to 64 levels of functions in a formula. Click the cell in which you want to enter the formula. Excel inserts the equal sign (=) for you.


2 Answers

Most probably you are having a linking error because:

void beep();

is a prototype of a function that has to be defined elsewhere. In C you can't define a function inside another one. Please, elaborate on the error you are getting.

like image 100
Khaled Alshaya Avatar answered Sep 30 '22 12:09

Khaled Alshaya


This is unusual but legal. The error you are seeing might be from the linker, if there is no actual beep() defined anywhere else. Can you post the actual error you receive?

like image 44
Jakob Borg Avatar answered Sep 30 '22 14:09

Jakob Borg