Recursive Main function - c

I have to make the code of a coffee dispenser in C.
I already have everything done and I just need to know how I can keep on running my "main" function until a certain condition is met (for example: util the machine can give no more change).
How can I achieve this?

I don't think you need a recursive main or for that matter any recursive function call at all for this. All you need is an infinite loop.
int main()
{
while (1) /* Infinite Loop */
{
... do stuff
if (condition is met)
break;
}
}

Related

Why does function not work when I add a function in it?

I am new at recursive functions.
int display(int num) {
if(num) {
display(num-1);
}
else {
return 0;
}
printf("\t%d", num);
}
When I run display(5), i can get "1 2 3 4 5" output as i want.
BUT:
When I add another function in this code and make some changes on the display() function and run the display(5) command it gives no output.. Here is the other code:
int bunnyEars2(int line) {
if(line == 0) {
return 0;
}
if(line % 2 == 1) {
return 2 + bunnyEars2(line-1);
}
else {
return 3 + bunnyEars2(line-1);
}
}
int display(int n) {
if(bunnyEars2(n)) {
display(bunnyEars2(n-1));
}
else {
return 0;
}
printf("\n%d", bunnyEars2(n));
}
I want to take bunnyEars2(1), bunnyEars2(2), bunnyEars2(3), bunnyEars2(4), bunnyEars2(5) outputs from display(5) command. But it gives no output. Can you help me out with this?
When you call display(5) it calls display(bunnyEars2(5)) which is display(12) => infinite loop
display(n) calls display(bunnyEars2(n-1)) and for every n>=2, bunnyEars2(n-1) > n so that you will get an infinite loop.
Other people have already given the reason for why this code is causing issues so I'll go into how to potentially look the causes of issues like this in the future.
When writing a recursive function, It is important to identify the various cases for your function. Each recursive function will have a set of cases which cause the function to call itself (recursive cases) and a set of functions in which the function will not call itself (base cases). In the case of the display function given in the first example. The recursive case is -- num has a non zero value, and the base case is -- num has a value of 0. A recursive function will only cease recursing if a function call hits a base case causing the recursive function calls to resolve rising up the call stack. Under any circumstance, any call to a recursive function does not lead a call of the function resulting in the execution of the base case, the call to the function will not resolve resulting in infinite recursion.
This infinite recursion is occurring in your second version of the display function. Look closely at the recursive case of your second display function.
if(bunnyEars2(n)){
display(bunnyEars2(n-1));
}
How would the value of bunnyEars2(n-1) compare to the value of n? Examine whether this recursive case will result in a calling of the function that executes a base case.
If you have access to a debugger and know how to use it, try stepping through the function and see what path it takes through the code. If you do not have access to a debugger, get some paper and a pencil and walk through the execution of your function by hand. This should give you a better idea about what your code is doing and how a problem might arise.

Force if statement to execute only once

I have a piece of code that will be executed many times (5,000+), and an if statement that will be true only the first time. I've thought of using a "FIRST" variable and compare it each time, but it just seems like a waste to check it every single time, even if I know it's not needed.
bool FIRST = true;
void foo(){
if(FIRST){
/* do something only once */
FIRST = false;
}
/* something something... */
}
I also don't know if there is some compiler optimization that does this automatically, or another way to do it; if there is, please let me know.
And yes, I know that a mere if statement isn't a big thing, but it just annoys me.
If you're using gcc, there are macros called unlikely and likely that can allow it to make optimizations based on a condition.
In your case the condition will only be true the first time, so you would use unlikely:
if (unlikely(FIRST)) {
From a compiler optimization point of view, I think an if statement is your best bet, as it will probably compile down to something like a single JNZ, so as long as FIRST stays true, it will be pretty optimized.
You might also want to take a look at this thread
You can call the function via a function pointer and remove the if check on the second call by changing the function pointer to a function without the if:
void foo_init(void);
void foo_real(void);
void (*foo)(void) = foo_init;
void foo_init(void) {
foo = foo_real;
/* do something only once */
foo_real();
}
void foo_real(void) {
/* something something... */
}
int main() {
foo();
foo();
}
Make foo and fooFirst, and then call like this
fooFirst();
for (...) {
foo();
}
foo and fooFirst can share code.

GtkSpinner with long-lasting function with C

I'm making a GTK+3 application in C and I want a spinner to show when the program is processing the data. Here's what I generally have:
main()
{
//Some statements
g_signal_connect(G_OBJECT(btnGenerate), "clicked", G_CALLBACK(Generate), &mainform);
}
void Generate(GtkWidget *btnGenerate, form_widgets *p_main_form)
{
gtk_spinner_start(GTK_SPINNER(p_main_form->spnProcessing));
Begin_Lengthy_Processing(Parameters, Galore, ...);
//gtk_spinner_stop(GTK_SPINNER(p_main_form->spnProcessing));
}
I have the stop function commented out so I can see the spinner spin even after the function has finished, but the spinner starts after the function is finished, and I suspect it turns on in the main loop.
I also found out that the entire interface freezes during the execution of the long going function.
Is there a way to get it to start and display inside the callback function? I found the same question, but it uses Python and threads. This is C, not Python, so I would assume things are different.
You need to run your lengthy computation in a separate thread, or break it up into chunks and run each of them separately as idle callbacks in the main thread.
If your lengthy computation takes a single set of inputs and doesn’t need any more inputs until it’s finished, then you should construct it as a GTask and use g_task_run_in_thread() to start the task. Its result will be delivered back to the main thread via the GTask’s GAsyncReadyCallback. There’s an example here.
If it takes more input as it progresses, you probably want to use a GAsyncQueue to feed it more inputs, and a GThreadPool to provide the threads (amortising the cost of creating threads over multiple calls to the lengthy function, and protecting against denial of service).
The GNOME developer docs give an overview of how to do threading.
This is what I got:
int main()
{
// Statements...
g_signal_connect(G_OBJECT(btnGenerate), "clicked", G_CALLBACK(Process), &mainform);
// More statements...
}
void Process(GtkWidget *btnGenerate, form_widgets *p_main_form)
{
GError *processing_error;
GThread *start_processing;
gtk_spinner_start(GTK_SPINNER(p_main_form->spnProcessing));
active = true;
if((start_processing = g_thread_try_new(NULL, (GThreadFunc)Generate, p_main_form, &processing_error)) == NULL)
{
printf("%s\n", processing_error->message);
printf("Error, cannot create thread!?!?\n\n");
exit(processing_error->code);
}
}
void Generate(form_widgets *p_main_form)
{
// Long process
active = false;
}
My program, once cleaned up and finished, as there are many other bugs in the program, will be put on GitHub.
Thank you all for your help. This answer comes from looking at all of your answers and comments as well as reading some more documentation, but mostly your comments and answers.
I did something similar in my gtk3 program. It's not that difficult. Here's how I would go about it.
/**
g_idle_add_full() expects a pointer to a function with the signature below:
(*GSourceFunc) (gpointer user_data).
So your function signature must adhere to that in order to be called.
But you might want to pass variables to the function.
If you don't want to have the variables in the global scope
then you can do this:
typedef struct myDataType {
char* name;
int age;
} myDataType;
myDataType person = {"Max", 25};
then when calling g_idle_add_full() you do it this way:
g_idle_add_full(G_PRIORITY_HIGH_IDLE, myFunction, person, NULL);
*/
int main()
{
// Assumming there exist a pointer called data
g_idle_add_full(G_PRIORITY_HIGH_IDLE, lengthyProcessCallBack, data, NULL);
// GTK & GDK event loop continues and window should be responsive while function runs in background
}
gboolean lengthyProcessCallBack(gpointer data)
{
myDataType person = (myDataType) *data;
// Doing lenghthy stuff
while(;;) {
sleep(3600); // hypothetical long process :D
}
return FALSE; // removed from event sources and won't be called again.
}

C Function Infinite Loop issue

I believe there is a simple solution to my issue, but my brain is too fried to think right now.
Inside my main function I have a function we will call "Function1". In "Function1" I call another function that verifies the data in "Function1", lets call this "Function2". In order for "Function2" to do its job well, it needs to call "Function1" again. This is obviously how I am getting an infinite loop of "Function1" and "Function2" repeatedly calling each other. I need to create method for tracking this so I can stop the loop after the first pass of Main --> Function1 --> Function2 --> Function1 --> End, but my implementation keeps failing.
I greatly appreciate any help and guidance.
You need to pass in a level counter to function1. On the first call the level is 0. If the level is 0, it can call function2. If it > 0 then do not call function2.
When function2 calls function1, it sets the level to 1 (or increases it).
This is how you do recursive calls. You can, of course, change the end condition to something else as needed (instead of just 0 and 1).
You could set a counter integer, and only run Function2 when the counter is less than 1 (or however many times you'd like the loop to iterate before breaking out).
For example (pseudocode):
int count;
Function1{
...
while(count < 1){
Function2{
.... //Function2 code
count++;
}
}
.. //any code from Function1 that should run after Function2
}
(Note, you could also do this with a boolean if you'd like - I prefer the integer approach, as you can change the number of iterations before breaking out fairly easily)

Switching between modes with an interrupt

I have two modes that I want to switch between with an interrupt that is generated by a sliding switch. Initially I read the current position and choose a mode/function. I want to switch between the two right when the position of the switch is changed. I have an interrupt which occurs on both edges (whenever the position is changed). However since both functions run continuously in a while loop, I can't just call them in the interrupt. Basically I have something like this:
interrupt()
{
//not sure how to switch between modes here
}
main()
{
//choose mode on startup
if (switch_HIGH)
modeA();
else
modeB();
}
modeA()
{
while(1)
{
//do something
}
}
modeB()
{
while(1)
{
//do something
}
}
I don't know if it's a good idea to just leave a function where it is and just move to something else but I can't think of any other way to do it. I'd really appreciate it if someone could tell me how I can go about this.
The language I'm using is C and the platform is a NIOS system on a Altera DE1 development board.
Using an interrupt for this seems very pointless; it's much simpler to just poll the input on each loop, and call the proper function just as you're doing.
UPDATE: I just relized your code doesn't have a loop, so the above is a bit hard to understand, of course.
I meant that you can structure your program like this:
int main(void)
{
initialize_hardware();
while(1)
{
if(switch_HIGH)
modeA();
else
modeB();
}
}
This makes the CPU go around in an infinite loop, and on each iteration it checks the switch and calls either modeA() or modeB() depending on the current mode.
Adding an interrupt gains you nothing except adding more complexity.
That said, what I would do is use a function pointer to indicate the current mode, and change the function pointer's value inside the interrupt, depending on the state of the switch. Then in the main loop just call the pointed-at function.
Remember to initialize the function properly, since you probably won't get an interrupt when teh device comes out of reset. This is another argument against this solution; the complexity is much bigger than just checking the switch on each iteration.
How about calling the two functions as threads. The interrupt function can kill the active thread and start the other thread. Pseudo code:
thread threada,threadb;
flag a=0;
interrupt()
{
if(a==0)
{
thread_kill(threada);
threadb=thread_create(modeB);
a=1;
}
else
{
thread_kill(threadb);
threada=thread_create(modeA);
a=0;
}
}
main()
{
thread_create(threada);
a=1;
}
modeA()
{
while(1)
{
//do something
}
}
modeB()
{
while(1)
{
//do something
}
}
Rather than killing the thread, you can have graceful shutdown mechanism using some kind of synchronization.

Resources