What does while(*pointer) means in C?

后端 未结 5 2082
心在旅途
心在旅途 2020-12-15 12:45

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 = &v         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-15 13:18

    Let's start with a simple example::

    int a = 2 ;
    int *b = &a ;
    /* Run the loop till *b i.e., 2 != 0 
    Now, you know that, the loop will run twice 
    and then the condition will become false 
    */
    while( *b != 0 )
    {
     *b-- ;
    }
    

    Similarly, your code is working with char*, a string.

    char var[10] ;
    /* copy some string of max char count = 9, 
    and append the end of string with a '\0' char.*/
    char *pointer = &var ;
    while( *pointer != '\0' )
    {
     // do something
     // Increment the pointer 1 or some other valid value
    }
    

    So, the while loop will run till *pointer don't hit '\0'.

    while( *pointer )
    /* The above statement means the same as while( *pointer != '\0' ),
    because, null char ('\0') = decimal value, numeric zero, 0*/
    

    But the usage can change when you do, while(*pointer != 'x'), where x can be any char. In this case, your first code will exit after *pointer hits the 'x' char but your second snippet will run till *pointer hits '\0' char.

提交回复
热议问题