Not at all - I believe you'll find do-nothing loops like these in K&R, so that's about as official as it gets.

It's a matter of personal preference, but I prefer my do-nothing loops like this:

while(something());

Others prefer the semicolon to go on a separate line, to reinforce the fact that it's a loop:

while(something())
  ;

Still others prefer to use the brackets with nothing inside, as you have done:

while(something())
{
}

It's all valid - you'll just have to pick the style you like and stick with it.

Answer from Kyle Cronin on Stack Overflow
๐ŸŒ
C2
wiki.c2.com
While Not Done Loop
This site uses features not available in older browsers
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 40335233 โ€บ true-or-false-in-c-programming-pertaining-to-while-loop
True or False in c programming pertaining to while loop - Stack Overflow
That means that foobar is true, 64 is true, -1 is true, and in your case, 1 is true. Because of this, the ! operator (the not symbol), it changes anything that is true into a 0, and changes a 0 into a 1.
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ i have a confusion concerning a while loops behavior with "c = getchar() !=eof" as the condition.
r/C_Programming on Reddit: I have a confusion concerning a while loops behavior with "c = getchar() !=EOF" as the condition.
August 10, 2023 -

From K&R chapter 1

    #include <stdio.h>
    int main (void) 
    {
    int c;
    while ((c = getchar()) != EOF) 
        putchar(c);
        
    }    

I run the program from Windows command line and I can enter:

Input: 5

5

Input: god help me

god help me

intput: djkslf4o3

djkslf4o3

and so on.

The program does not terminate unless I press ctrl-z(followed by /n) or ctrl-c (using windows command line). I also read from another source that ctrl-z is actually "signalling EOF", causing getchar() to return -1 which is EOF's value (please fact check me).

I see this in the terminal and it contradicts my (obviously wrong) understanding of what exactly EOF is doing and what its purpose is.

In the case I type 45 and hit enter: I assume that after putchar(c) is called twice in the loop, EOF is returned by getchar(). The while loop's condition is now false. I cannot reconcile, my conceptualization of the necessity of EOF acting as the brakes in a senseโ€” I type 45 into the terminal and I get only 45 back and not 45 followed by an ongoing stream of random bytes

with

my understanding of the program as a whole where I would like to assert that after the while loop's condition evaluates to false, the program would terminate. But it doesn't terminate. Does this suggest that we haven't exited the loop and EOF is not being returned by getchar(), after reading my input 45? But then how does the putchar() know when to stop?

Is windows thinking ahead for me and running the program over again with every successive input into the terminal? Am I misunderstanding the while loop?

Also, if it is indeed the case "that '^z\n' (windows) is actually signalling EOF, causing getchar() to return -1", considering my observation that this terminates the program, this confuses me again when considering the former logic. If this does indeed terminate the loop by causing getchar() to return -1, is it not so that the loop also needs to be terminated for every successive input in order for the input x into the terminal, to only be output as x and not x followed by random garbage in memory?

Would greatly appreciate any help thanks.

Top answer
1 of 5
21
The behavior is confusing because the terminal is doing part of the job here. When you type a character, the terminal doesn't send it to your program immediately: it puts it into a buffer, and this buffer is only sent when you press enter. At that moment, there is a whole line of characters waiting to be read by getchar(), and your program reads them and prints them. But enter is not EOF, it's just enter, so after that the while loop is still running, waiting for more characters that it will only get when you press enter, and so on.
2 of 5
13
If I understand you right, I think your confusion is from the fact that you have the impression that getchar() has to return quickly. But it doesn't, and that's actually what happens. If there's no characters waiting to be sent to your program (and no EOF signaled, so some more could still be coming) then getchar() simply doesn't return until there's new information to report. In that way it's a "blocking" operation - it will stop your program's execution for an unknown amount of time until whatever condition it's waiting for finishes. The blocking aspect for getchar() is useful for simple programs like the one you wrote. Note how the program doesn't use 100% CPU (which a normal while() loop with no pausing would do). That's because when getchar() blocks, it does so in a way that doesn't require any CPU power, instead it basically tells the OS "don't run me again until there's more characters typed in" (where "me" is your process).
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do while not loops work
r/learnpython on Reddit: How do while not loops work
September 11, 2024 -

I was reading through this code and I'm just not getting how while loops work when not operator is also used.

https://pastebin.com/5mfBhQSb

I thought the not operator just inversed whatever the value was but I just can't see this code working if that's the case.

For example , the while not sequenceCorrect should turn the original value of False to True, so the loop should run while it's True. But why not just state while True then? And why declare sequenceCorrect = True again? Doesn't it just means while True, make it True? And so on.

The only way it makes sense to me is of the while not loop always means False (just like the while always means as long as it's True) even if the value is supposed be False and should be inverted to True.

So, is that the case? Can anyone explain why it works like that?

Top answer
1 of 8
7
In general, recall the while loop syntax. while : Conceptually, coding aside, consider filling a glass of water. Is there space for more water in the glass? Okay, then pour some. Without going in detail of how this funky glass object is defined, hopefully the following makes sense as a python analog of that process. while glass.has_space(): #we're still filling the glass glass.add_water() #glass is now full of water Without writing out how this glass object works, let's say it has another method for returning a boolean (True/False) for whether or not it is currently full, instead of the previous example of whether or not it had space for more water. We can fill the glass in the same way, but we have to negate that statement using the not operator while not glass.is_full(): #we're still filling the glass glass.add_water() #glass is now full of water Going back to the initial syntax, which is still the same, the only thing we've done is changing the condition statement of the loop. Instead of checking that glass.has_space() evaluates to True, we are now checking that the expression not glass.is_full() evaluates to True. That is the same statement as evaluating that glass.is_full() evaluates to False, because the only thing the not operator does to a boolean is negating it, i.e. True becomes False and vice versa. Now looking at your code linked, the condition for looping is that not sequenceCorrect evaluates to True, which is equivalent to the statement that sequenceCorrect is False. I won't paste the code here, but we see on line 3 that sequenceCorrect starts its life being False, so upon entering the while loop we do indeed step into that block of code because at that time not sequenceCorrect is in fact True. Then the first thing we do on line 5 is reassign it to True. If the remaining lines don't change it back to False, this will stop the while loop from repeating, since in this current state not sequenceCorrect evaluates to False. So you can say that line 5 is defaulting the loop to not going to be repeated. The only way for the loop to be repeated is for lines 6-8 with the nested for loop and if statement to find some character in dna that is not in "actgn", upon which sequenceCorrect will be assigned to False and thus the statement in the while loop not sequenceCorrect would evaluate to True and thus the loop would repeat itself once more. Personally, I think this is just a pretty unclear way to achieve the goal of checking the validity of that input string. I would have defined it another way, but I can't see anything wrong with it really. If the not operation in the while loop statement is bothering you, you could equally have rewritten the code with a variable for instance named sequenceIncorrect and just flipped all assignments i.e. True's become False's and vice versa.
2 of 8
2
The difference here is that by using not sequenceCorrect you are avoiding the use of the break keyword. It's cleaner and makes the loop terminate itself, rather than relying on a specific keyword and force terminate it. You could use while True, but that way is not descriptive enough and can potentially create and endless loop if you don't take care of the edge cases. Think about it: while not sequenceCorrect is telling you, without a single comment line, that the loop should run while sequenceCorrect is False, vs while True which the only thing that's telling you is that this loop will run endlessly for unknown reasons.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ difference-while1-while0-c-language
Difference between while(1) and while(0) in C language - GeeksforGeeks
November 8, 2022 - In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The boolean condition is either true or false. ... It is an infinite loop which will run till a break statement is issued explicitly. Interestingly not while(1) but any integer which is non-zero will give a similar effect as while(1).
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_while_loop.php
C While Loop
Loops are handy because they save time, reduce errors, and they make code more readable. The while loop repeats a block of code as long as a specified condition is true:
Find elsewhere
๐ŸŒ
Codecademy Forums
discuss.codecademy.com โ€บ computer science
Trouble with my 'while' something is 'not true' do something code. please help - Computer Science - Codecademy Forums
December 16, 2022 - Hi all. 1 week into c++ learning loops. Iโ€™m trying to put something into a loop that says - whilst the answer is not 1 or 2, enter humber again. This is what Iโ€™ve done. Itโ€™s not working. keeps repeating loop even if condโ€ฆ
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ why is my while loop not working? (c language)
r/learnprogramming on Reddit: Why is my while loop not working? (C language)
January 30, 2021 -

I'm making a link list to rearrange some letters to point to each other in alphabetical order. When I run the code in Command prompt it does not show any errors however no output is given. I tested my code with some print statements to see where the error is and I saw that everything before the while condition gets executed. I also think I made mistakes in inserting strings into the nodes as well so that might also be a factor. Anyways can someone help me out, please?

#include <stdio.h>

#include <stdlib.h>

struct studentname

{

char letter;

struct studentname *next;

};

typedef struct studentname STUDENTName;

typedef STUDENTName *STUDENTNamePtr;

int main()

{

//creating 5 empty nodes

STUDENTNamePtr node1 = (STUDENTName\*)malloc(sizeof(STUDENTName));

STUDENTNamePtr node2 = (STUDENTName\*)malloc(sizeof(STUDENTName));

STUDENTNamePtr node3 = (STUDENTName\*)malloc(sizeof(STUDENTName));

STUDENTNamePtr node4 = (STUDENTName\*)malloc(sizeof(STUDENTName));

STUDENTNamePtr node5 = (STUDENTName\*)malloc(sizeof(STUDENTName));


//fill the values  ----> s,e,n,a,d


node1->letter = 's';

node1->next = NULL;



node2->letter = 'e';

node2->next = NULL;



node3->letter = 'n';

node3->next = NULL;



node4->letter = 'a';

node4->next = NULL;



node5->letter = 'd';

node5->next = NULL;


//linking ----> a,d,e,n,s


node4->next = node5;      // a -> d

node5->next = node2;      // d -> e

node2->next = node3;      // e -> n

node3->next = node1;      // n -> s

//printing

STUDENTNamePtr current;

current = node4;

while(current != NULL)

{

	printf("%s--->", current->letter);

	current = current->next;

}

printf("NULL\\n");
return 0;

}

๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how to stop a while (true) command in c?
r/learnprogramming on Reddit: How to stop a while (true) command in C?
May 27, 2022 -

If I have a while (true) statement that has an if function in it like this:

while (true)

{

if (n > 8)

{

printf("hi");

}

}

When the if statement is false (n is smaller than 8), the code just does nothing, it seems like the code stays in the while true statement and keeps asking if the if statement is true or false. How do you make the while true command stop and go to the next line of code when it's finished?

Thank you.

๐ŸŒ
Quora
quora.com โ€บ Why-cant-we-use-instead-of-in-a-while-loop
Why can't we use == instead of ! = in a while loop? - Quora
Answer (1 of 5): Of course you can use == instead of != in while loop. It depends on what problem statement is. Here is the demo code in C language which will run infinite times: [code]#include int main(){ int a = 5; while(a==5) { printf("%d",a); } return 0; } [/code]Here in the abo...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ cprogramming โ€บ c_while_loop.htm
C - While Loop
Since the expression that controls the loop is tested before the program enters the loop, the while loop is called the entry verified loop. Here, the key point to note is that a while loop might not execute at all if the condition is found to be not true at the very first instance itself.
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 52007-when-while-loop-will-stop.html
when a while loop will stop ?
1. while(false ) // bool false --> loop will stop 2. while(NULL) ----> loop will stop 3. while(0) ----->loop will stop 4. while('\0') -----> loop will stop. i think there are many more conditions like above... so there are basically different rules. is there any other condition which can make the while loop stop ? ... Anything that reduces to a boolean false will stop a while loop, thus... while ( 1 == 2 ) ... will do. The other examples you give, (some of which may or may not work with all compilers), are simply examples of this.
๐ŸŒ
Arduino Forum
forum.arduino.cc โ€บ projects โ€บ programming
What is the difference between while(){} and while(); - Programming - Arduino Forum
April 25, 2016 - I have not had any formal C (and variants) training, but learn by reading and experimenting. I have had college training in the late 80's in BASIC (also self taught while in high school, ah the good old days) , FORTRAN, โ€ฆ
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_do_while_loop.php
C Do While Loop
C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... The do/while loop is a variant of the while loop.
๐ŸŒ
Quora
quora.com โ€บ What-does-while-t-do-exactly-in-C
What does while(t--) {โ€ฆ} do exactly in C? - Quora
This while loop will run until the value of t becomes zero. AS tโ€” decrements the value of t every time it checks for the condition of while loop so at some point of time the value will reach to zero at the time while loop will not be executed and the control will come out of the loop.