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
}
Can be turned into this:
//While Loop Part:
while(*pointer){
//Something to Loop
}
So, my problem is, what does *pointer means?
The while statement lets you repeat a statement until a specified expression becomes false.
The * operator turns a value of type pointer to T into a variable of type T . The & operator turns a variable of type T into a value of type pointer to T .
A pointer in C and C++ programming is a variable that points to an address of another variable and not its value. When creating a pointer, use an asterisk (*); when determining the address of the variable, the ampersand (&), or the address-of operator, will display this value.
Example 1: while loopWhen i = 1 , the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2 . Now, i = 2 , the test expression i <= 5 is again true.
while(x) {
do_something();
}
will run do_something()
repeatedly as long as x
is true. In C, "true" means "not zero".
'\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).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With