这个三元表达式的等价if else语句是什么?

What would be the equivalent if else statement of this ternary expression?

本文关键字:if else 语句 是什么 表达式 三元      更新时间:2023-10-16
bool wm(const char *s, const char *t)
{
    return *t-'*' ? *s ? (*t=='?') | (toupper(*s)==toupper(*t)) && wm(s+1,t+1) : !*t : wm(s,t+1) || *s && wm(s+1,t);
}

我在网上搜索了三进制/if else等价物,但这个似乎很奇怪,因为它在开头有一个返回。

来自cplusplus网站:(条件)?(if_true): (if_false)

if(a > b){
    largest = a;
} else if(b > a){
    largest = b;
} else /* a == b */{
    std::cout << "Uh oh, they're the same!n";
}

谢谢

实际上是两个三元语句。

if (*t-'*' ) {
  if (*s) {
    return (*t=='?') | (toupper(*s)==toupper(*t)) && wm(s+1,t+1);
  } else {
    return !*t;
  }
} else {
  return wm(s,t+1) || *s && wm(s+1,t);
}

开头的return只返回整个语句的结果。

在你的例子中,你可以这样写:

bool wm(const char *s, const char *t)
{
    if(*t-'*')
    {
        if (*s)
           return (*t=='?') | (toupper(*s)==toupper(*t)) && wm(s+1,t+1);
        else
           return !*t;
    }
    else
        return wm(s,t+1) || *s && wm(s+1,t);
}

return不是三元表达式的一部分。你可以这样想:

return (
  *t-'*' ? *s ? (*t=='?') | (toupper(*s)==toupper(*t)) && wm(s+1,t+1) : !*t : wm(s,t+1) || *s && wm(s+1,t)
);

要将其复制为if语句,您需要在单独的分支中放置return语句:

if (*t-'*') {
  if (*s) {
    return (*t=='?') | (toupper(*s)==toupper(*t)) && wm(s+1,t+1);
  } else {
    return !*t;
  }
} else {
  return wm(s,t+1) || *s && wm(s+1,t);
}