Anidh Singh
Anidh Singh

Reputation: 324

Use of just while(x)

#include<stdio.h>
#include<conio.h>

/* Function Declaration
int pal(int x); */
/*Declaring Second Function*/

int rev(int x);

int main()
{
    int a, b, c;
    clrscr();

    printf("Enter The Number Which You Want To Check Is Palindrome Or Not\n");
    scanf("%d", &a);

    b = rev(a);
    printf("%d", b);

    if(b == a) {
        printf("%d Is A Palindrome Number", a);
    } else {
        printf("%d Isn't A Plaindrome Number", a);
    }

    getch();
    return(0);
}

int rev(int x)
{
    int d = 0;

    while(x) {
        d = d * 10 + x % 10;
        x = x / 10;
    }
    return(d);
}

I didn't get the use of while(x) statement. I mean, we attach some condition with while loop i.e. while(x!=0), so what does standalone while(x) means.

Upvotes: 1

Views: 23371

Answers (1)

user93353
user93353

Reputation: 14049

while (x) is the same as while (x != 0)

For an integral data type, 0 is false & everything else is true. So while (x) would evaluate to while(true) for all x != 0.

Similarly, you will also come across expressions like while(!x) or if(!x)

If x has value a non zero value, then x is true & !x is false. If x has value 0, then x is false & !x is true.

So writing (!x) is the same as writing (x == 0)

You will also see similar usage with pointers. For a pointer p, (p) is the same as (p != NULL) and (!p) is the same as (p == NULL).

Upvotes: 11

Related Questions