我想了解编译过程.我们可以使用以下命令查看预处理器中间文件:
gcc -E hello.c -o hello.i
Run Code Online (Sandbox Code Playgroud)
要么
cpp hello.c > hello.i
Run Code Online (Sandbox Code Playgroud)
我大致知道预处理器的作用,但我很难理解某些行中的数字.例如:
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "hello.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 374 "/usr/include/features.h" 3 4
Run Code Online (Sandbox Code Playgroud)
这些数字可以帮助调试器显示行号.所以我对第一列的猜测是第2列文件的行号.但是以下数字有什么作用?
我在Ruby中遇到了一个有趣的表达:
a ||= "new"
Run Code Online (Sandbox Code Playgroud)
这意味着如果未定义a,则将"new"值分配给a; 否则,a将与它相同.在进行一些数据库查询时很有用.如果设置了该值,我不想触发另一个数据库查询.
所以我在Python中尝试了类似的思维方式:
a = a if a is not None else "new"
Run Code Online (Sandbox Code Playgroud)
它失败了.我认为这是因为你不能在Python中做"a = a",如果a没有定义.
所以我可以出来的解决方案是检查locals()和globals(),或者使用try ... except表达式:
myVar = myVar if 'myVar' in locals() and 'myVar' in globals() else "new"
Run Code Online (Sandbox Code Playgroud)
要么
try:
myVar
except NameError:
myVar = None
myVar = myVar if myVar else "new"
Run Code Online (Sandbox Code Playgroud)
我们可以看到,解决方案并不那么优雅.所以我想问一下,有没有更好的方法呢?