gpt4 book ai didi

c++ - 指针问题 : Odd function output when one line of code is added

转载 作者:太空宇宙 更新时间:2023-11-04 15:43:47 24 4
gpt4 key购买 nike

在我的课本中有一个函数叫做streq检查字符串是否相等。我复制了这段代码并决定添加 cout << *s1 << endl;在返回 false 之前查看打印出来的内容。但是,我注意到如果两个输入字符串相等并且我添加了额外的代码,它将返回 false。

#include <iostream>
using namespace std;

bool streq(const char* s1, const char* s2);

int main()
{
const char A [] = "Hello";
const char B [] = "Hello";

cout << streq(A,B) << endl;
}

bool streq(const char* s1, const char* s2)
{
int count = 0;

while (*s1 != 0 && *s2 != 0)
if (*s1++ != *s2++)
cout << *s1 << endl;
return false;
count++;
return (*s1 == *s2);
}

但是,如果我注释掉我添加的代码,该函数将正常运行并返回 true (1)。有谁知道这里的问题是什么?

最佳答案

尽管有缩进,这段代码

if (*s1++ != *s2++)
cout << *s1 << endl;
return false;

相当于:

if (*s1++ != *s2++)
{
cout << *s1 << endl;
}
return false;

这就是为什么你的修改改变了程序的逻辑。 if 条件控制下一条语句,仅一条语句。如果需要多个语句,则需要使用 block 。

if (*s1++ != *s2++)
{
cout << *s1 << endl;
return false;
}

这正是为什么有些人选择始终使用带有 ifelse 的 block ,即使后面只有一个语句。当您稍后需要添加更多语句时,它不太容易出错。

关于c++ - 指针问题 : Odd function output when one line of code is added,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com