Home > Mobile >  While loop using a variable with no condition
While loop using a variable with no condition

Time:12-11

So I've seen this used before some of my profs code aswel as in some of my friends who have more experience with programming.

int number = 0;
while(number) {

a bunch of code

}

My understanding is that this while loop is essentially running with no condition, i feel like it should be while(number = 0) { Isnt this essentially creating an infinite loop? but in the cases I've seen it used it can break out of the loop somehow.

edit: do while that uses the argument in question. Note that the 2 functions being called in the switch case will call searchpatientdata again once they have completed.

This code is not currently wokring, but was working in a previous build and this function was the same. They also do not change the selection variable either.

CodePudding user response:

The condition in a while loop can be any expression of scalar (numeric or pointer) type. The condition is treated as false if the result of evaluating the expression is equal to zero, true if it's non-zero. (For a pointer expression, a null pointer is equal to zero).

So while (number) means while (number != 0).

As a matter of style, I prefer to use an explicit comparison unless the variable is logically a Boolean condition (either something of type bool or _Bool, or something of some integer type whose only meaning values are true and false) -- but not everyone shares my opinion, and while (foo) is a very common way to write while (foo != 0).

The same applies to the condition in an if, a do-while, or a for statement.

Note that in your example:

int number = 0;
while(number) {
    // a bunch of code
}

the body of the loop will never execute, because number is equal to zero when the loop is entered. More realistically, you might have:

int number = some_value;
while (number) {
    // a bunch of code *that can change the value of number*
}

CodePudding user response:

any place in c where a boolean value is required any int will be evaluated like this

  • 0 => false
  • not zero => true

CodePudding user response:

From C reference

Executes a statement repeatedly, until the value of expression becomes equal to zero. The test takes place before each iteration.

How it works?

  1. entry control loop
  2. condition is checked before loop execution
  3. never execute loop
  4. if condition is false there is no semicolon at the end of while statement

Come to point as per OP's question yes While (Variable_name) evaluated as True

In below Example While loop executes until condition is true

Example:

#include <stdio.h>
#include <stdbool.h>
int main(void) 
{
    int num=1;
    while(true)
    {
        if(num==5)
        {       
            break;
        }
        printf("%d\n",num);
        num  ;
    }
return 0;
}
  • Related