你怎么称呼在有条件的情况下做作业?
What do you call doing assignment in a conditional?
在条件语句中做赋值有专门的名称吗?这是我在 C:
中询问的示例
// Assume a and b have been previously defined and are compatible types
if( (a = b) ) { // <- What do you call that?
//do something
}
我和我的几个朋友确信它有一个名字,其他一些人也同意有一个名字,但我们到处都找不到。这里有人听过这个词吗?
它并没有真正的名字,尽管人们确实给它起了各种各样的名字。如果代码遵循您的问题:
if( a = b )...
那么常见的术语有:bug, error, etc. 但是如果 b
不是变量而是表达式,例如与常见的 C 模式一样:
if( (c = getchar()) != EOF )...
while( *q++ = *p++ )...
那么它可能被称为习语、模式等
假设赋值是有意的,对此没有特殊的名称。 C 语言规范对 if
语句的控制表达式提出了非常弱的要求:
6.8.4.1-1: The controlling expression of an if statement shall have scalar type.
赋值表达式满足这个要求,只要 a
和 b
是标量。对这个赋值的结果执行与零的隐式比较:
6.8.4.1-2: In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0.
请注意,编译器在看到这样的赋值时会发出警告,因为缺少第二个 =
是常见的错误来源。 You can prevent these warnings using parentheses, as described in this Q&A.
我不知道它有没有名字,但我会称之为“没有人理解的有用功能”。
这确实非常有用。
我们可以认为它是俚语。
例如在 C++ 中,您可以通过直接声明变量来使用它,这对于安全检查很有用:
if (Object *a = takeObject()) {
// a 不是 nullptr
}
或者当我不想在循环中重复一个语句时:
while (a = next()) {
}
而不是:
a = next();
while (a) {
a = next();
}
但通常这些只是 gcc 和 clang 等编译器发出警告的错误(并且它们会强制您放置一个可怕的双元组来消除警告 ew!)。
在条件语句中做赋值有专门的名称吗?这是我在 C:
中询问的示例// Assume a and b have been previously defined and are compatible types
if( (a = b) ) { // <- What do you call that?
//do something
}
我和我的几个朋友确信它有一个名字,其他一些人也同意有一个名字,但我们到处都找不到。这里有人听过这个词吗?
它并没有真正的名字,尽管人们确实给它起了各种各样的名字。如果代码遵循您的问题:
if( a = b )...
那么常见的术语有:bug, error, etc. 但是如果 b
不是变量而是表达式,例如与常见的 C 模式一样:
if( (c = getchar()) != EOF )...
while( *q++ = *p++ )...
那么它可能被称为习语、模式等
假设赋值是有意的,对此没有特殊的名称。 C 语言规范对 if
语句的控制表达式提出了非常弱的要求:
6.8.4.1-1: The controlling expression of an if statement shall have scalar type.
赋值表达式满足这个要求,只要 a
和 b
是标量。对这个赋值的结果执行与零的隐式比较:
6.8.4.1-2: In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0.
请注意,编译器在看到这样的赋值时会发出警告,因为缺少第二个 =
是常见的错误来源。 You can prevent these warnings using parentheses, as described in this Q&A.
我不知道它有没有名字,但我会称之为“没有人理解的有用功能”。 这确实非常有用。 我们可以认为它是俚语。
例如在 C++ 中,您可以通过直接声明变量来使用它,这对于安全检查很有用:
if (Object *a = takeObject()) { // a 不是 nullptr }
或者当我不想在循环中重复一个语句时:
while (a = next()) {
}
而不是:
a = next();
while (a) {
a = next();
}
但通常这些只是 gcc 和 clang 等编译器发出警告的错误(并且它们会强制您放置一个可怕的双元组来消除警告 ew!)。