Use of just while(x)

送分小仙女□ 提交于 2021-02-16 15:06:30

问题


#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.


回答1:


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).



来源:https://stackoverflow.com/questions/25699689/use-of-just-whilex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!