关于如何不使用分号打印 hello world 一直是一个热门问题。我知道很多代码,但这一个听起来很奇怪,因为我无法理解它背后的逻辑。请帮助我知道它是如何打印的。
if(printf("hello world")){}
最佳答案
关于分号的一点只是有点“我比你聪明”的误导。
然而,当你得到这个你就会对c有所了解;
这里有一系列可能有用的程序。编译并运行每一个,然后思考它们的作用以及它们与之前的有何不同:
#include <stdio.h>
int main(void) {
int i = printf("Hello, world!\n");
printf("%d\n",i);
return 0;
}
#include <stdio.h>
int main(void) {
if ( 1 ) {
printf("condition evaluated as true\n");
} else {
printf("condition evaluated as false\n");
}
return 0;
}
#include <stdio.h>
int main(void) {
if ( printf("Hello, world!\n") ) {
printf("condition evaluated as true\n");
} else {
printf("condition evaluated as false\n");
}
return 0;
}
#include <stdio.h>
int main(void) {
if ( printf("Hello, world!\n") ) {
}
return 0;
}
最后,您可以省略 main 的返回(在这种情况下隐式返回 0)。所以你得到:
#include <stdio.h>
int main(void) {
if ( printf("Hello, world!\n") ) {
}
}
这是 Hello, world! 的完整、符合标准的版本!没有任何分号。
关于c - 这个 if 语句如何避免使用分号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3747501/