while(* pointer)在C中意味着什么? [英] What does while(*pointer) means in 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
(如果x
是int
,short
等)或x != '\0'
(如果x
是char
) )与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')
,则x
是char
,并且要一直继续下去,直到找到一个空字符(您可能正在处理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屋!