c - 短路 if 语句
问题描述
假设你有这个嵌套的 if 语句:
int *x;
int y;
if (x == NULL || y > 5)
{
if (x != NULL)
// this should print if x != NULL and y > 5
printf("Hello!\n");
// this should only print if x == NULL.
printf("Goodbye!\n");
}
return 0;
在这里,如果任一语句为真,它将返回相同的值 (0)。如果外部 if 语句的左侧为真,我们应该只打印“再见”,而不管右侧是真还是假。是否可以通过短路来消除内部 if 语句,将其变成单个 if 语句?
解决方案
如果我理解正确,您需要的是以下内容
if ( x == NULL )
{
printf("Goodbye!\n");
}
else if ( y > 5 )
{
printf("Hello!\n");
}
否则,如果第一个复合语句包含在 x == NULL 或 y > 5 时必须执行的其他语句,则 if 语句看起来像
if ( x == NULL || y > 5)
{
// common statements that have to be executed when x == NULL or y > 5
//...
if ( !x )
{
printf("Goodbye!\n");
}
else
{
printf("Hello!\n");
}
}
推荐阅读
- javascript - 如何让 DataTables 搜索与 AJAX 结果一起正常工作?
- javascript - 为什么我的 API 调用函数返回一个未定义的对象?
- python - 如何在没有 python 控制台的情况下运行 tkinter 应用程序
- python - 如何获取与用户模型一对一相关的对象
- google-bigquery - Google Data Studio - BigQuery 数据源列表,如何跟踪用作数据源的 bigquery 表
- c - 如何清除已在 C 编程中使用的字符串的内容?
- c# - 我在 while 循环中的计数出现错误,C# Visual Studio
- coq - Coq 中的证明模式定义?
- angular - ngFor 不显示自定义迭代器的值
- protocol-buffers - Protobuf 消息可以以 gzip 幻数开头吗?