有时,在C语言中,我喜欢在同一行上赋值和检查一个条件变量——主要是为了在隔离代码部分(例如,而不仅仅是编写代码)的同时进行自我文档化
if ( 1 ) { ... }
),而无须写
#ifdef
. 让我举一个例子:
#include <stdio.h>
#include <stdbool.h>
int main() {
bool mytest;
if ( (mytest = true) ) {
printf("inside %d\n", mytest);
}
printf("Hello, world! %d\n", mytest);
return 0;
}
这就是你所期望的:如果你有
if ( (mytest = true) ) {
,程序的输出为:
inside 1
Hello, world! 1
... 如果你写信
if ( (mytest = false) ) {
,程序的输出为:
Hello, world! 0
(考虑到在
if
警告:将赋值结果用作不带括号的条件[-wParenthes]
")
天真的方法似乎不起作用:
$ python3
Python 3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> mytest = None
>>> if ( (mytest=True) ): print("inside {}".format(mytest))
File "<stdin>", line 1
if ( (mytest=True) ): print("inside {}".format(mytest))
^
SyntaxError: invalid syntax
it has
-这就是为什么我要问这个问题。