Ad

Is While(*pointer) Legal In C?

I recently came across a lot of code snippets that use:

while (*pointer) { 
    ... ++pointer; 
}

I checked it with my lecturer whether it is good and "legal" to perform such an action, Because I thought the condition would not stop in case of pointer to integers array.

I could not get a clear answer, I would appreciate any answer if it is correct to use this case and why the condition works because it is not certain that at the end of the array will be 0 / NULL that will stop the condition.

Thanks in advance.

Ad

Answer

Good and legal, yes. This is used a lot.

An example, and you want to use a pointer instead of an index (that has some advantages sometimes).

Counting the number of * in a string

int counstar(char *s) {
    int n = 0;
    while(*s) if(*s++ == '*') n++;
    return n;
}

Usually, (convention) C strings are ending with a '\0', thus you know where it ends, and me mere if (*s) suffices.

For integers (and anything but strings), unless it's been specified (eg last number is 0), you don't know the size of the array, and need a variable to tell the size. However, if you know that the last one is zero, for instance, the algo would be similar to the string one above.

Adding x to n integers

void addx(int *a, int x, int n) {
   while (n--) *a++ += x;
}

If you know the last item is always 0 (and is not incremented)

void addx(int *a, int x) {
   while (*a) *a++ += x;
}
Ad
source: stackoverflow.com
Ad