Nested functions and its usefulness, functions that call one after another? - c

I have seen people write code in this fashion:
void function2()
{.....
..more blah blah...
.<I think i will stop nesting my function here>...
..blah blah. over and out....
}
void function1()
{.....
..blah blah...
function2();
....
}
void LCD_disp_main ()
{
<automatic, static... variable declaration>
....
function1(); //calling a function 1
.....
}
as opposed to writing the definitions that you would normally put in function and put it inline here.
void LCD_disp_main ()
{
<automatic, static... variable declaration>
....
<function1() and function2();> //instead of calling function1 and fucntion2 just inline it here.
.....
}
What is the benefit of one over the other?
Doesn't the first set cause the stack to keep growing everytime you call a new function albeit it will grow the same mount in option 2? Context switching?

Well, it's for readability, maintainability and obeying the convention that a function should do one thing only and do it well and lots of other benefits as well. Imagine how you would write a callback if you lump all your code into a single function. If you are so worried about the size of the stack frame why don't you write everything in the main() function?
BTW, context switching does not apply here, it's used to define the process of swapping processes / threads off the processor.

These are not "nested functions". It is true that on a poor compiler it would waste more stack. However putting into functions makes the code a) reusable, b) groups related things together.
An optimizing compiler would know to inline the contents of all these functions so the resulting code would be more or less identical for both cases - especially if the functions were declared with internal linkage (i.e. the keyword static).

Related

What is the best way to detect that a recursive function is called by another function, not by function itself?

Suppose I have a recursive function rec_fun() and it have two block of code, block_1 and block_n. block_1 must execute only once when rec_fun() is initially called by another function like main() and block_n must execute every time rec_fun() is called, whether by another function or by function itself.
rec_fun()
{
{
...
//block_1
//must be executed on first call only
...
}
{
...
//block_n
//with recursive call and exit condition
...
}
}
What is the best way to achieve this? I have thought few ways like using a counter i as parameter to rec_fun() initially passed with 0 and incrementing it in subsequent call, so that the function can determine whether it is first call or not. Another approach is to put block_n in another helper function and call it from rec_fun(). But in first approach I have to pass an unnecessary argument 0 and second approach creates an unnecessary function. What is the best way to accomplish this, according to you?
I'll appreciate if you provide some useful links to learn recursion.
Hide it behind a layer of indirection:
func()
{
//block_1
// compute what you need
// and pass it to rec_fun either as value, or as a pointer
rec_func(&block_1_result);
}
And make sure you expose only func for your users.
and second approach creates an unnecessary function
So? Unless you are in an extremely limited environment like an embedded device with very limited memory that's really not an issue. And the function is not "unnecessary". It's unnecessary if you think the user doesn't need 2 functions, but it's necessary if you think from the implementation view: it's needed by the implementation (actually it's one solution, but still the argument holds).
I will go against your intuition completely and will suggest to combine the two approaches you consider inappropriate. Because they are appropriate. I will create a recursive implementation with extra parameter, but for convenience and "hiding" I will also make a wrapper function:
void rec_func(bool init)
{
if (init) {
/* initialization logoc */
}
/* common recursive code */
rec_func(false);
}
void wrapper_func(void)
{
rec_func(true);
}
Note, nothing is "unnecessary" here. The extra parameter helps to keep the function logic in one unit. The wrapper function helps the caller not to mess with unrelated parameters.
Your second solution is usually the correct one.
The second function isn't any less necessary than any other function. You have one function that defines what is needed to implement whatever it is that the external caller expects your code to do. You have another to define whatever it is that you're going to do recursively.
Those apparently do different things and meet different requirements. As such, it's entirely appropriate that they be implemented in different functions.
It's possible to combine these into a single function that varies its behavior depending on a parameter that's passed. If the difference in behavior is small enough, this can be a somewhat reasonable approach--but I would say having one function do two different sorts of things is generally a kludge. The only question is whether it's a small enough kludge that you choose to overlook its being kludgy, or a big enough one that you shouldn't overlook it.
As so ensuring that the second function isn't accidentally called by some "outsider", the usual is to make it a static function, so you'd have a structure on this general order:
foo.h
#pragma once
int foo(int);
foo.c
typedef result_t /* whatever */;
static result_t blocka(int) {
// stuff for block a
}
static int blockb(result_t const *) {
// stuff for block b
}
int foo(int input) {
result_t internal_result = blocka(input);
return blockb(&internal_result);
}
In this case, I've written both blocka and blockb as separate "unnecessary" functions. Since I don't know what either your block a or block b does, it's hard to guess whether that's justified or not. But I would not start by thinking in terms of whether a function is necessary. Rather the opposite, for almost any block of code with a reasonably well defined interface and functionality, writing a function to embody that block of code should be more or less the default.
For example, if you have an if/then/else kind of situation:
if (foo) {
// do foo stuff
} else {
// do not-foo stuff
}
Think about/ask yourself whether you can give a meaningful name to the "do foo stuff" block and/or the "do not-foo stuff" blocks. That is, can you give a name to what they're doing?
If so, there's a reasonable chance that they should be implemented as functions, and then your if/then/else block can become a more readable, higher-level guide to what's going on:
if (data_sorted(input))
process_sorted_data(input);
else
process_random_data(input);
Moving these blocks of code into (reasonably well-named) functions makes it much easier for a reader to understand the intent behind the code, rather than having to divine your intent from the content.
The C language does not give the function any information regarding its caller so there is no portable way to test whether rec_fun() was called from another function or recursively from itself.
Your goal can be achieved by passing an extra argument to the function with a different value for outsider and recursive calls. This is cumbersome and error prone.
The standard approach for your problem is to use an ancillary function rec_fun1(): the main function rec_fun() is called from other functions and the recursive ancillary function is called from rec_fun() and recursively from rec_fun1() itself.
A classic example of this is mergesort() which would allocate the temporary work array and call a recursive mergesort1() that uses the temporary array to perform the top down merge sort algorithm. Upon return from the call to mergesort1(), mergesort() frees the temporary array and returns to the caller.
You can use static variable as counter.
rec_fun()
{
static int i = 0;
if (++i == 1) {
...
//block_1
//must be executed on first call only
...
}
{
...
//block_n
//with recursive call and exit condition
...
}
--i; // internal house keeping to track whether internal, or external caller
}
You can pass a parameter that you change as you move down the recursion and make block 1 ran based on the condition of the parameter. If you use an if/else if for block 1 and 2 then you're good.
your_func(the_param){
if(the_param) {
// the code that only runs on the first call
}
else if(the_param) {
// the code that runs every other call
}

Functions that call each other, declared inside another function

I have two functions that call each other, inside of another function:
int main(){
void aaa();
void b(){
aaa();
}
void aaa(){
b();
}
aaa();
}
(Yes, this example would be stuck in an infinite loop or cause a stack overflow)
The compiler throws the error: static declaration of 'aaa' follows non-static declaration
If I move the function declarations outside of the other function, it works (but I can't do that because those functions need to have access to main's local variables)
Is it possible to make this work?
C does not support nested functions, nor closures.
One solution for your actual problem is to define the shared state (the local variables of main you mentioned, in this case) as struct, then have variable of this struct type, and pass it as pointer to the functions that use it.
You don't show the local variable code in your question, so I'm not writing and arbitrary example. Please edit the question with more code, if you want an example.
Another solution is to just use global (preferably static) variables, used both from other functions and main. I mean, since main isn't a normal function (can't be called recursively by standard, for example), its local variables end up being unique objects anyway, so this is just a matter of scope and visibility, with little to no funcional difference.

Error: Expected a “;” Visual Studio 2013 [duplicate]

This is not a lambda function question, I know that I can assign a lambda to a variable.
What's the point of allowing us to declare, but not define a function inside code?
For example:
#include <iostream>
int main()
{
// This is illegal
// int one(int bar) { return 13 + bar; }
// This is legal, but why would I want this?
int two(int bar);
// This gets the job done but man it's complicated
class three{
int m_iBar;
public:
three(int bar):m_iBar(13 + bar){}
operator int(){return m_iBar;}
};
std::cout << three(42) << '\n';
return 0;
}
So what I want to know is why would C++ allow two which seems useless, and three which seems far more complicated, but disallow one?
EDIT:
From the answers it seems that there in-code declaration may be able to prevent namespace pollution, what I was hoping to hear though is why the ability to declare functions has been allowed but the ability to define functions has been disallowed.
It is not obvious why one is not allowed; nested functions were proposed a long time ago in N0295 which says:
We discuss the introduction of nested functions into C++. Nested
functions are well understood and their introduction requires little
effort from either compiler vendors, programmers, or the committee.
Nested functions offer significant advantages, [...]
Obviously this proposal was rejected, but since we don't have meeting minutes available online for 1993 we don't have a possible source for the rationale for this rejection.
In fact this proposal is noted in Lambda expressions and closures for C
++ as a possible alternative:
One article [Bre88] and proposal N0295 to the C
++ committee [SH93] suggest adding nested functions to C
++ . Nested functions are similar to lambda expressions, but are defined as statements within a function body, and the resulting
closure cannot be used unless that function is active. These proposals
also do not include adding a new type for each lambda expression, but
instead implementing them more like normal functions, including
allowing a special kind of function pointer to refer to them. Both of
these proposals predate the addition of templates to C
++ , and so do not mention the use of nested functions in combination with generic algorithms. Also, these proposals have no way to copy
local variables into a closure, and so the nested functions they
produce are completely unusable outside their enclosing function
Considering we do now have lambdas we are unlikely to see nested functions since, as the paper outlines, they are alternatives for the same problem and nested functions have several limitations relative to lambdas.
As for this part of your question:
// This is legal, but why would I want this?
int two(int bar);
There are cases where this would be a useful way to call the function you want. The draft C++ standard section 3.4.1 [basic.lookup.unqual] gives us one interesting example:
namespace NS {
class T { };
void f(T);
void g(T, int);
}
NS::T parm;
void g(NS::T, float);
int main() {
f(parm); // OK: calls NS::f
extern void g(NS::T, float);
g(parm, 1); // OK: calls g(NS::T, float)
}
Well, the answer is "historical reasons". In C you could have function declarations at block scope, and the C++ designers did not see the benefit in removing that option.
An example usage would be:
#include <iostream>
int main()
{
int func();
func();
}
int func()
{
std::cout << "Hello\n";
}
IMO this is a bad idea because it is easy to make a mistake by providing a declaration that does not match the function's real definition, leading to undefined behaviour which will not be diagnosed by the compiler.
In the example you give, void two(int) is being declared as an external function, with that declaration only being valid within the scope of the main function.
That's reasonable if you only wish to make the name two available within main() so as to avoid polluting the global namespace within the current compilation unit.
Example in response to comments:
main.cpp:
int main() {
int foo();
return foo();
}
foo.cpp:
int foo() {
return 0;
}
no need for header files. compile and link with
c++ main.cpp foo.cpp
it'll compile and run, and the program will return 0 as expected.
You can do these things, largely because they're actually not all that difficult to do.
From the viewpoint of the compiler, having a function declaration inside another function is pretty trivial to implement. The compiler needs a mechanism to allow declarations inside of functions to handle other declarations (e.g., int x;) inside a function anyway.
It will typically have a general mechanism for parsing a declaration. For the guy writing the compiler, it doesn't really matter at all whether that mechanism is invoked when parsing code inside or outside of another function--it's just a declaration, so when it sees enough to know that what's there is a declaration, it invokes the part of the compiler that deals with declarations.
In fact, prohibiting these particular declarations inside a function would probably add extra complexity, because the compiler would then need an entirely gratuitous check to see if it's already looking at code inside a function definition and based on that decide whether to allow or prohibit this particular declaration.
That leaves the question of how a nested function is different. A nested function is different because of how it affects code generation. In languages that allow nested functions (e.g., Pascal) you normally expect that the code in the nested function has direct access to the variables of the function in which it's nested. For example:
int foo() {
int x;
int bar() {
x = 1; // Should assign to the `x` defined in `foo`.
}
}
Without local functions, the code to access local variables is fairly simple. In a typical implementation, when execution enters the function, some block of space for local variables is allocated on the stack. All the local variables are allocated in that single block, and each variable is treated as simply an offset from the beginning (or end) of the block. For example, let's consider a function something like this:
int f() {
int x;
int y;
x = 1;
y = x;
return y;
}
A compiler (assuming it didn't optimize away the extra code) might generate code for this roughly equivalent to this:
stack_pointer -= 2 * sizeof(int); // allocate space for local variables
x_offset = 0;
y_offset = sizeof(int);
stack_pointer[x_offset] = 1; // x = 1;
stack_pointer[y_offset] = stack_pointer[x_offset]; // y = x;
return_location = stack_pointer[y_offset]; // return y;
stack_pointer += 2 * sizeof(int);
In particular, it has one location pointing to the beginning of the block of local variables, and all access to the local variables is as offsets from that location.
With nested functions, that's no longer the case--instead, a function has access not only to its own local variables, but to the variables local to all the functions in which it's nested. Instead of just having one "stack_pointer" from which it computes an offset, it needs to walk back up the stack to find the stack_pointers local to the functions in which it's nested.
Now, in a trivial case that's not all that terrible either--if bar is nested inside of foo, then bar can just look up the stack at the previous stack pointer to access foo's variables. Right?
Wrong! Well, there are cases where this can be true, but it's not necessarily the case. In particular, bar could be recursive, in which case a given invocation of bar might have to look some nearly arbitrary number of levels back up the stack to find the variables of the surrounding function. Generally speaking, you need to do one of two things: either you put some extra data on the stack, so it can search back up the stack at run-time to find its surrounding function's stack frame, or else you effectively pass a pointer to the surrounding function's stack frame as a hidden parameter to the nested function. Oh, but there's not necessarily just one surrounding function either--if you can nest functions, you can probably nest them (more or less) arbitrarily deep, so you need to be ready to pass an arbitrary number of hidden parameters. That means you typically end up with something like a linked list of stack frames to surrounding functions, and access to variables of surrounding functions is done by walking that linked list to find its stack pointer, then accessing an offset from that stack pointer.
That, however, means that access to a "local" variable may not be a trivial matter. Finding the correct stack frame to access the variable can be non-trivial, so access to variables of surrounding functions is also (at least usually) slower than access to truly local variables. And, of course, the compiler has to generate code to find the right stack frames, access variables via any of an arbitrary number of stack frames, and so on.
This is the complexity that C was avoiding by prohibiting nested functions. Now, it's certainly true that a current C++ compiler is a rather different sort of beast from a 1970's vintage C compiler. With things like multiple, virtual inheritance, a C++ compiler has to deal with things on this same general nature in any case (i.e., finding the location of a base-class variable in such cases can be non-trivial as well). On a percentage basis, supporting nested functions wouldn't add much complexity to a current C++ compiler (and some, such as gcc, already support them).
At the same time, it rarely adds much utility either. In particular, if you want to define something that acts like a function inside of a function, you can use a lambda expression. What this actually creates is an object (i.e., an instance of some class) that overloads the function call operator (operator()) but it still gives function-like capabilities. It makes capturing (or not) data from the surrounding context more explicit though, which allows it to use existing mechanisms rather than inventing a whole new mechanism and set of rules for its use.
Bottom line: even though it might initially seem like nested declarations are hard and nested functions are trivial, more or less the opposite is true: nested functions are actually much more complex to support than nested declarations.
The first one is a function definition, and it is not allowed. Obvious, wt is the usage of putting a definition of a function inside another function.
But the other twos are just declarations. Imagine you need to use int two(int bar); function inside the main method. But it is defined below the main() function, so that function declaration inside the function makes you to use that function with declarations.
The same applies to the third. Class declarations inside the function allows you to use a class inside the function without providing an appropriate header or reference.
int main()
{
// This is legal, but why would I want this?
int two(int bar);
//Call two
int x = two(7);
class three {
int m_iBar;
public:
three(int bar):m_iBar(13 + bar) {}
operator int() {return m_iBar;}
};
//Use class
three *threeObj = new three();
return 0;
}
This language feature was inherited from C, where it served some purpose in C's early days (function declaration scoping maybe?).
I don't know if this feature is used much by modern C programmers and I sincerely doubt it.
So, to sum up the answer:
there is no purpose for this feature in modern C++ (that I know of, at least), it is here because of C++-to-C backward compatibility (I suppose :) ).
Thanks to the comment below:
Function prototype is scoped to the function it is declared in, so one can have a tidier global namespace - by referring to external functions/symbols without #include.
Actually, there is one use case which is conceivably useful. If you want to make sure that a certain function is called (and your code compiles), no matter what the surrounding code declares, you can open your own block and declare the function prototype in it. (The inspiration is originally from Johannes Schaub, https://stackoverflow.com/a/929902/3150802, via TeKa, https://stackoverflow.com/a/8821992/3150802).
This may be particularily useful if you have to include headers which you don't control, or if you have a multi-line macro which may be used in unknown code.
The key is that a local declaration supersedes previous declarations in the innermost enclosing block. While that can introduce subtle bugs (and, I think, is forbidden in C#), it can be used consciously. Consider:
// somebody's header
void f();
// your code
{ int i;
int f(); // your different f()!
i = f();
// ...
}
Linking may be interesting because chances are the headers belong to a library, but I guess you can adjust the linker arguments so that f() is resolved to your function by the time that library is considered. Or you tell it to ignore duplicate symbols. Or you don't link against the library.
This is not an answer to the OP question, but rather a reply to several comments.
I disagree with these points in the comments and answers: 1 that nested declarations are allegedly harmless, and 2 that nested definitions are useless.
1 The prime counterexample for the alleged harmlessness of nested function declarations is the infamous Most Vexing Parse. IMO the spread of confusion caused by it is enough to warrant an extra rule forbidding nested declarations.
2 The 1st counterexample to the alleged uselessness of nested function definitions is frequent need to perform the same operation in several places inside exactly one function. There is an obvious workaround for this:
private:
inline void bar(int abc)
{
// Do the repeating operation
}
public:
void foo()
{
int a, b, c;
bar(a);
bar(b);
bar(c);
}
However, this solution often enough contaminates the class definition with numerous private functions, each of which is used in exactly one caller. A nested function declaration would be much cleaner.
Specifically answering this question:
From the answers it seems that there in-code declaration may be able to prevent namespace pollution, what I was hoping to hear though is why the ability to declare functions has been allowed but the ability to define functions has been disallowed.
Because consider this code:
int main()
{
int foo() {
// Do something
return 0;
}
return 0;
}
Questions for language designers:
Should foo() be available to other functions?
If so, what should be its name? int main(void)::foo()?
(Note that 2 would not be possible in C, the originator of C++)
If we want a local function, we already have a way - make it a static member of a locally-defined class. So should we add another syntactic method of achieving the same result? Why do that? Wouldn't it increase the maintenance burden of C++ compiler developers?
And so on...
Just wanted to point out that the GCC compiler allows you to declare functions inside functions. Read more about it here. Also with the introduction of lambdas to C++, this question is a bit obsolete now.
The ability to declare function headers inside other functions, I found useful in the following case:
void do_something(int&);
int main() {
int my_number = 10 * 10 * 10;
do_something(my_number);
return 0;
}
void do_something(int& num) {
void do_something_helper(int&); // declare helper here
do_something_helper(num);
// Do something else
}
void do_something_helper(int& num) {
num += std::abs(num - 1337);
}
What do we have here? Basically, you have a function that is supposed to be called from main, so what you do is that you forward declare it like normal. But then you realize, this function also needs another function to help it with what it's doing. So rather than declaring that helper function above main, you declare it inside the function that needs it and then it can be called from that function and that function only.
My point is, declaring function headers inside functions can be an indirect method of function encapsulation, which allows a function to hide some parts of what it's doing by delegating to some other function that only it is aware of, almost giving an illusion of a nested function.
Nested function declarations are allowed probably for
1. Forward references
2. To be able to declare a pointer to function(s) and pass around other function(s) in a limited scope.
Nested function definitions are not allowed probably due to issues like
1. Optimization
2. Recursion (enclosing and nested defined function(s))
3. Re-entrancy
4. Concurrency and other multithread access issues.
From my limited understanding :)

Is function invocation at translation time valid?

I'm trying to achive a function to be called only one time. But I want to save the if (firstTime) check.
What I'm thinking about was:
while (1)
{
foo();
}
foo()
{
static int test = 1, srand (test);
test++;
}
But I couldn't find anything in the standard what is covering this.
So I'm not sure about, this is undefined. And if not so, will srand be invoked as expected? If not so, is it (as the main question is) even possible to invoke functioncalls on translationtime (what would more be, behave as if), as I'm doing here?
As an option to a first time flag, you could use a pointer to function that is initially set to the first time function, which in turn would set the pointer to function to the actual function. There's a level of indirection, but it eliminates a conditional branch.
A more general version of this idea is to use the pointer to function as a "state machine", where each function "advances" (sets) the pointer to the next state (the next function as part of a series of functions). This can be handy for event or interrupt driven code. I've used this method for device drivers and embedded code.
Your idea is probably that using a function call as an initializer for a static variable would call that function only once a program startup.
No, this is not possible in C, only constants are allowed in that context. In C++ this would be possible, and the compiler applies some secret wisdom to know in which order such initializations are effected.

Does using a prototype + definition instead of just a definition speed up the program?

Im very new to C programing, but have limited experience with Python, Java, and Perl. I was just wondering what the advantage is of having the prototype of a function above main() and the definition of that function below main() rather than just having the definition of said function above main(). From what I have read, the definition can act as a prototype as well.
Thanks in advance,
The use of a prototype above main() (within a single module) is mostly a matter of personal preference. Some people like to see main() at the bottom of the file; other people like to see it at the top. I had a professor in university who complained that I wrote my programs "upside-down" because I put main() at the bottom (and avoided having to write and maintain prototypes for everything).
There is one situation where a prototype may be required:
void b(); // prototype required here
void a()
{
b();
}
void b()
{
a();
}
In this mutually recursive situation, you need at least one of the prototypes to appear prior to the definition of the other function.
When someone else wants to use your library, you can give them the header (containing the prototypes), without giving them your code.
Example? Windows SDK.
If two functions call each other, you will need to have a prototype for at least one of them.
There is no performance impact* on the compiled code.
*Note: Well, there could be, I guess. If the compiler decides to put the method somewhere else in the binary, then you could theoretically see locality issues affecting the performance of your application. It's not something to normally worry about, though.
There's no advantage in splitting a function into a standalone prototype and a definition. In fact, there's a clear and explicit disadvantage to that approach, since it requires extra maintenance efforts to keep the prototype and the definition in perfect sync. For this reason, a reasonable approach would be to provide a separate prototype only when you have to. For example, with external functions declared in header files you have no other choice but to keep the prototype and definition separate.
As for functions internal to a single translation unit (the ones that we'd normally declare static) there's absolutely no reason to create a standalone prototype, since the definition of the function itself includes a prototype. Just define your functions in the natural order: low level functions first, high level functions last, and that's it. If your program consists of a single translation unit, the main function will end up at the very bottom.
The only case you'd have to declare a standalone prototype in this approach would be if some form of recursion was involved.
If you write your code in the correct order, i.e. main last, then there is only one definition in your code for each function. This prevents having to change the code in two, or more, places if changes ever need to be made. That prevents errors and reduces the work to maintain it. The principle is called "single source of truth"

Resources