while(* pointer)在C中意味着什么? [英] What does while(*pointer) means in C?

查看:113
本文介绍了while(* pointer)在C中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我最近看一些有关C指针的文章时,我发现了一些有趣的东西.它说的是这样的代码:

When I recently look at some passage about C pointers, I found something interesting. What it said is, a code like this:

char var[10];
char *pointer = &var;
while(*pointer!='\0'){
    //Something To loop
}

可以变成这样:

//While Loop Part:
while(*pointer){
    //Something to Loop
}

所以,我的问题是, *指针是什么意思?

So, my problem is, what does *pointer means?

推荐答案

while(x) {
    do_something();
}

只要x为true,

将重复运行do_something().在C语言中,"true"表示非零".

will run do_something() repeatedly as long as x is true. In C, "true" means "not zero".

'\0'是一个空字符.在数字上为零(表示'\0'的位与数字零相同;就像空格是数字0x20 = 32).

'\0' is a null character. Numerically, it's zero (the bits that represents '\0' is the same as the number zero; just like a space is the number 0x20 = 32).

所以您有while(*pointer != '\0').而指向内存的不是零字节.之前,我说过"true"表示非零",因此比较x != 0(如果xintshort等)或x != '\0'(如果xchar) )与if,while等内的x相同.

So you have while(*pointer != '\0'). While the pointed-to -memory is not a zero byte. Earlier, I said "true" means "non-zero", so the comparison x != 0 (if x is int, short, etc.) or x != '\0' (if x is char) the same as just x inside an if, while, etc.

您应该使用这种较短的形式吗?我认为没有.对于阅读代码的人来说,它的含义不太清楚.如果您显式地编写比较,则即使在技术上对编译器意味着相同的意思,也使循环的意图更加明显.

Should you use this shorter form? In my opinion, no. It makes it less clear to someone reading the code what the intention is. If you write the comparison explicitly, it makes it a lot more obvious what the intention of the loop is, even if they technically mean the same thing to the compiler.

因此,如果您编写while(x),则x应该是一个布尔值或一个已经表示布尔值的C int(一个正确或错误的概念).如果编写while(x != 0),那么您会关心x是一个非零整数,并且正在使用x进行数值运算.如果您写while(x != '\0'),则xchar,并且要一直继续下去,直到找到一个空字符(您可能正在处理C字符串).

So if you write while(x), x should be a boolean or a C int that represents a boolean (a true-or-false concept) already. If you write while(x != 0), then you care about x being a nonzero integer and are doing something numerical with x. If you write while(x != '\0'), then x is a char and you want to keep going until you find a null character (you're probably processing a C string).

这篇关于while(* pointer)在C中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆