Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Simple question regarding while loops in C...

+3 votes
asked Oct 12, 2021 by Ethan Mopht Farsi (150 points)
I am trying to run a simple program where the variable ledwill alternate between 1 and 0 with a delay in between (infinitely).

#include <stdio.h>
#include <unistd.h>
int function()
{
   for(;;)  
   {  
        int led =1;
        sleep(0.5);
        led=0;
       
   }  
return 0;  
}

Checking my work I inserted a printf in between at different points but the output still gives me nothing, I was wondering what the problem may be. Thank you in advance!

2 Answers

+1 vote
answered Oct 13, 2021 by di Caprio Alessio (160 points)

Hi!
I think that the problem is linked to the function...there isn't a main function and the program won't be compilated correctly. So, the program report in console the error "ld returned 1 exit status" If a've right understand.
 

Try to do this:
I've just tried and it works good
 

#include <stdio.h>
#include <unistd.h>
int main()
{
   int led;
   for(;;)  
   {  
    led =1;
    sleep(0.5);
    printf("Led: %d \n", led);
    led=0;
    printf("Led: %d \n", led);
       
   }  
return 0;  
}

Here is the output

- Ale

 

0 votes
answered Oct 13, 2021 by Peter Minarik (84,720 points)
edited Oct 14, 2021 by Peter Minarik

You must have a main() function in your program. That's the entry point. If there's no entry point provided, then your program doesn't do anything, no matter how long code you have written.

sleep() takes an unsigned int for an argument, but you're giving it a double (0.5), which is cast to int and turned into 0.

Your code correctly:

#include <stdio.h>
#include <unistd.h>

int function()
{
    int led = 1;
    while (true)
    {
        printf("led: %d\n", led);
        sleep(1);
        led = !led;
    }
    return 0;
}

int main()
{
    return function();
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...