IF 条件和 && OPERATOR 的问题

Problem with IF condition and && OPERATOR

我在我的代码中遇到了一个主要问题,当我点击 1 并且 j 为 5 时,尽管布尔函数 returns False,IF 语句仍然设法运行。

#include <iostream>
using namespace std;
#include <string>

using namespace std;

bool checkSym(string s, int left, int right) {
  if (left >= right)
    return true;
  else {
    if (int(s[left]) != int(s[right]))
      return false;
    else {
      checkSym(s, left + 1, right - 1);
    }
  }
}
int main() {
  // TODO
  string s, c, d;
  s = "babadad";
  int max = 0;
  int n = s.length();
  for (int i = 0; n - i >= max; i++) {
    c = "";
    for (int j = max; j <= n - i; j++) {
      c = s.substr(i, j);
      if (checkSym(c, 0, j - 1) && j > max) {
        max = j;
        d = c;
      }
    }
  }
  cout << d;
}

代码看起来不可读。不过至少这个功能

bool checkSym(string s, int left, int right) {
  if (left >= right)
    return true;
  else {
    if (int(s[left]) != int(s[right]))
      return false;
    else {
      checkSym(s, left + 1, right - 1);
    }
  }
}

可以调用未定义的行为,因为它returns此代码段中没有任何内容

    else {
      checkSym(s, left + 1, right - 1);
    }

你需要写

    else {
      return checkSym(s, left + 1, right - 1);
    }

也不清楚为什么使用显式转换类型 int

 if (int(s[left]) != int(s[right]))

而不只是写作

 if ( s[left] != s[right])