Do we need a test condition to run a for loop?

Joined
Dec 19, 2022
Messages
2
Reaction score
1
my question is can we run a for loop in c without a test condition?
like this:
for( ; ; )
will this run the code in the for block or will this turn out to be false?
 
Joined
Jul 4, 2023
Messages
366
Reaction score
41
Yes you can use for ( ;; ) loop as infinite loop, e.g.
[ on-line ]
C:
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#include <unistd.h> // For sleep function

int main() {
    initscr(); // Initialize ncurses

    printf("Press 'q' to exit...\n");
    sleep(2);
    clear();
    refresh();
   
    cbreak(); // Enable 'cbreak' mode, which doesn't wait for Enter key
    noecho(); // Disable echoing of typed characters
    nodelay(stdscr, TRUE); // Set getch() to be non-blocking

    for (;;) {
        int ch = getch(); // Read a single character without blocking

        if (ch == 'q') {
            printf("Exiting...\n");
            sleep(2);
            break;
        }

        printf("Message every 1 second...\n");
        refresh(); // Refresh the ncurses screen
        sleep(1); // Wait for 1 second
    }

    endwin(); // End ncurses

    return 0;
}
 
Joined
Sep 3, 2023
Messages
2
Reaction score
0
my question is can we run a for loop in c without a test condition?
like this:
for( ; ; )
will this run the code in the for block or will this turn out to be false?
Yes, you can run a for loop in C without a test condition, like this:

for( ; ; ) {
// Code to be executed indefinitely
}

In this case, the for loop will run indefinitely because there is no test condition provided within the parentheses. It will keep executing the code block within the loop repeatedly until it encounters a break statement or some other exit condition within the loop body. This is often referred to as an infinite loop. To exit such a loop, you would typically use a break statement or another control flow mechanism, as there is no built-in test condition to exit it automatically.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top