简体   繁体   English

字符和布尔表达式相加会导致布尔结果吗?

[英]Is Addition of Char and Boolean Expression results in Boolean result?

In the following function 在以下功能

The statement s[i] + s[i] == c; 语句s[i] + s[i] == c; results in either zero or one (Boolean result). 结果为零或一(布尔结果)。

My question: will the above expression be converted to boolean expression? 我的问题:上面的表达式会转换为布尔表达式吗? It is considering the value of s[i] 正在考虑s[i]的值

void func(char s[], int c)
{
    int i, j;
    for (i = j = 0; s[i] != '\0'; i++)
        if (s[i] != c)
            s[j++] = s[i] + s[i] == c;
    s[j] = '\0';
}

Your premise is incorrect. 您的前提不正确。 The expression s[i] + s[i]==c is equivalent to (s[i] + s[i]) == c . 表达式s[i] + s[i]==c等于(s[i] + s[i]) == c Therefore, it is not "addition of char and boolean expression". 因此,它不是“字符和布尔表达式的加法”。

The result is a boolean expression, but note that there is no primitive bool type in C. So this expression will be of type int , with a value of either 1 or 0 . 结果是一个布尔表达式,但是请注意,C中没有原始bool类型。因此,该表达式的类型为int ,值为10 So therefore, the value of s[j] will be either 1 or 0 . 因此, s[j]的值将为10

There is no boolean type in C, at least not unless you dive into the mostly unused parts of the standard. C中没有布尔类型,至少没有,除非您深入了解该标准中大多数未使用的部分。

Expressions that, semantically speaking, have boolean values, are managed by the compiler as int s with value 1 (for true) and 0 (for false). 从语义上讲,具有布尔值的表达式由编译器以int进行管理,它们的值分别为1(表示true)和0(表示false)。 You can then assign that value to a char , and it will be appropiately down-casted/demoted. 然后,您可以将该值分配给char ,它将适当地向下转换/降级。

This: 这个:

char a, b, c;
a = (b == c);

Works like this: 像这样工作:

char a, b, c;
a = (b == c) ? 1 : 0;

Both 1 and 0 are of integer type, demoted to char on assignment. 1和0均为整数类型,在分配时降级为char。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM