r/learnprogramming • u/Orange_Doakes • Mar 24 '26
What is the best way to replace functions within functions?
So a long time ago I have made a hobby project that was a sudoku solver.
A few years later I tried to compile it in visual studio or something and found a bunch of errors.
It turned out I (knowingly or not, I don't remember) used a quirk of the gcc that allows for functions to be defined within other functions.
I'm thinking of refactoring the code so that it will be actually up to the C standard and I wander what is the best way to go about it.
So far I figure I can turn this:
int foo(){
int b = 2;
int bar(){
return b+5;
}
return bar();
}Into this:
int bar_in_foo(int b){
return b+5;
}
int foo(){
int b = 2;
return bar_in_foo(b);
}or this If necessary:
int bar_in_foo(int *b){
return *b+5;
}
int foo(){
int b = 2;
return bar_in_foo(&b);
}But I wonder if that's the best way and I'm also curious what would be the best way to deal with that if I switched to C++.
2
u/alexppetrov Mar 24 '26 edited Mar 24 '26
Genuinely curious, what is the use case for function within functions? Private in-scope functions for code readability or something else?
Other than that, I would rewrite the project to newer standards and try to do some refactoring to reduce complexity
Edit: nvm I checked and the use case is similar to closures, so I get it. Still, point stands, either create a "library" to abstract the logic or move the nested methods away
1
u/BlueGnoblin Mar 24 '26
You should always start with not declaring functions inside functions. What you should learn about are
2
u/ThrowRAClueBoy Mar 24 '26
Please use proper variable names
2
u/owjfaigs222 Mar 24 '26
Yeah, the way you want to do the refactoring, should work.
In C++ you could use lambdas, they essentially can work as your "functions within functions".
1
u/HashDefTrueFalse Mar 24 '26
Just move the functions out of others, or delete them altogether if they serve no real purpose. Whether your functions take input and produce output (pure functions) or produce side effects (e.g. writing to memory via a pointer) is up to you. It often depends on the size of the data you want to pass up and down the call stack.
C++ is the same if you're writing it C-style, but modern C++ has lambdas that work basically the same as in other languages that can be defined inside functions. For older C++ standards you can fall back to local classes/structs with static member functions if you really want to. I'd rarely see a need, personally.
1
u/imaami Mar 24 '26
You can put
externfunction declarations inside functions. It's a nice way to call external functions from inline functions without having to declare them in file scope. Not the same as truly private methods, but useful.