Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

loops - What does while(*pointer) means in 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!=''){
    //Something To loop
}

Can be turned into this:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
while(x) {
    do_something();
}

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

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

So you have while(*pointer != ''). 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 != '' (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.

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 != ''), then x is a char and you want to keep going until you find a null character (you're probably processing a C string).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...