下面的代碼旨在斷言一個字符串是否包含某個前綴。 函數prefix
僅在給定的字符串包含前綴pre
時才返回1。for循環中的布爾條件C
/* 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;
}
編譯並運行後,assert (errCode == 1)
失敗。 我通過gdb運行它,發現在for循環裏面的prefix
函數, 行if (pre[i] != str[i]) return 0;
即使在pre[i] == '\000'
時也被執行。 此時不應滿足for循環中的條件,並且最後一次比較不會被執行? 我意識到,將條件從||
更改爲&&
確實是我的第一意思,但我不明白爲什麼,這是我的問題。如何在pre[i] == '\000'
時仍然執行以下條件 pre[i] != '\0' || str[i] != '\0'
?