Haru Frost
Haru Frost

Reputation: 237

Checking for string null terminators in C

I know what the null-terminator in C is represented by \0 and has the numerical value of 0. However, when I execute the following code below, the program treats the null terminator as %. I searched this up online but I couldn't find anyone with this issue.

int main(){
    char* forward = "hello";
    int forward_length = 0;
    while (*(forward++) != '\0') {
        printf("%d\n", forward_length++);
    }
    if(*forward == '%'){
        printf("Terminator Found");
    }
}

The output is:

0
1
2
3
4
Terminator Found

Clearly, forward[5] does not equal the char %. Can someone please let me know what is wrong with the program?

Upvotes: 0

Views: 835

Answers (1)

Joshua
Joshua

Reputation: 43327

The construction leaves forward advanced too far. This is because the post-increment will run even if the loop condition is false (as it is inside the loop condition). The obvious fixed loop is as follows:

   for (;*forward != '\0'; ++forward)
       printf("%d\n", forward_length++);

If you prefer to keep the while loop, --forward after the while loop will fix it.

Upvotes: 1

Related Questions