c - 这个 if 语句如何避免使用分号?

标签 c

关于如何不使用分号打印 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/

相关文章:

c++ - C代码分解器

c++ - 我无法找到这些代码段的 Big O 表示法

c - 工作线程在一段时间后退出

无法让 execvp 执行文件

c - 小C程序运行

c - Linux 模块 __must_check 注解

c - c99 语义中的存储类说明符 'register'

c - 如何查看组和其他用户的权限?

c - free() 使代码崩溃

CUDA 驱动程序 API 等效于 cudaSetDevice