【发布时间】:2015-07-06 01:33:41
【问题描述】:
以下
#include <iostream>
unsigned short int stringCompare ( char * s1, char * s2 )
{
// returns 1 if the character arrays s1 and s2 are equal;
// returns 0 otherwise
while (*s1 && (*s1++ == *s2++));
return (!(*s1) && !(*s2));
}
int main ()
{
char str1 [] = "americano";
char str2 [] = "americana";
std::cout << stringCompare(str1,str2);
return 0;
}
打印1,表示我的函数逻辑不正确。我想了解为什么。让我解释一下我的逻辑:
while (*s1 && (*s1++ == *s2++))
同时递增指针s1 和s2,只要s1 不等于'\0' 并且s1 指向的值与s2 指向的值相同。应该是比较短的写法
while (*s1 && *s2)
{
if (*s1 != *s2) break;
++s1; ++s2;
}
并依靠花哨的运算符优先级来缩短它。
声明
return (!(*s1) && !(*s2))
表示
"If s1 and s2 are both the null character, return true; otherwise return false"
因为如果字符串相等,那么s1 和s2 在while 循环之后都是空字符。
我哪里错了?
【问题讨论】:
-
您是否考虑过简单地逐步执行算法?你会很快发现问题...