Question

The following code is intended to assert if a string contains a certain prefix. The function prefixreturns 1 only if the string given contains the prefix pre.

/* preprocessor directives */
#include <stdlib.h>
#include <assert.h>

/* prototypes */
int prefix(char * pre, char * str);

int main() {
    /* declaration / initialization */
    char pre[] = "Hell", str1[] = "Hello!", str2[] = "hi!";
    int errCode = prefix(pre, str1);

    /* processing */
    assert (errCode == 1);
    errCode = prefix(pre, str2);
    assert (errCode == 0);

    errCode = prefix(NULL, str2);
    assert (errCode == 0);
        errCode = prefix(pre, NULL);
    assert (errCode == 0);

    /* termination */
    return 0;
}

/* Returns 0 if pre or str is NULL or if pre is not a prefix of str.
 * Otherwise returns 1.
 */
int prefix(char * pre, char * str) {
        /* declaration / initialization */
    int i;

    /* processing */
    if (pre == NULL || str == NULL) return 0;

    for (i = 0; pre[i] != '\0' || str[i] != '\0'; i++)
        if (pre[i] != str[i]) return 0;

    if (pre[i] != '\0') return 0;

    /* termination */
    return 1;
}

After compilation and running, assert (errCode == 1) fails. I run it through gdb and find out that in the for loop inside prefix function, the line if (pre[i] != str[i]) return 0; is executed even when pre[i] == '\000'. Shouldn't the condition in the for loop be met at this point and this last comparison not to be executed?? I realized that changing the for condition from ||to && does what i meant in the first place, yet i do not understand why and this is my question. How come the following condition pre[i] != '\0' || str[i] != '\0' is still executed when pre[i] == '\000'?

Was it helpful?

Solution

You are using ||..ie logical or which evaluates to true if any one of values is true

So for condition pre[i] != '\0' || str[i] != '\0', although pre[i]='\0', str[i]!='\0'. So condition evaluates to true and it enters the loop.

What you need to use is &&..ie logical and

In simple terms, loop until both the strings are not '\0', This is achieved by

pre[i] != '\0' && str[i] != '\0'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top