逻辑运算符:

运算符 含义 优先级
! 逻辑非
&& 逻辑与
|| 逻辑或

举例:

!a:如果 a 为真,!a 为假;如果 a 为 假,!a 为真

a && b:a 和 b 同时为真,结果才为真;a 和 b 有一个为假,结果就为假

a || b:a 和 b 有一个为真或 a 和 b 全为真,结果就为真;a 和 b 全为假,结果才为假

逻辑表达式:

用逻辑运算符将两边的变量、数据或表达式连接起来,称之为逻辑表达式

#include <stdio.h>

int main()
{
printf("%d\n", 3 > 1 && 1 < 2);
printf("%d\n", 3 < 1 && 1 < 2);
printf("%d\n", !(1));
printf("%d\n", !0 + 1 < 1 || !(3 + 1));
printf("%d\n", 'a' - 'b' && 'c'); return 0;
}

运行结果

!0 + 1 < 1 || !(3 + 1):!0 等于 1,1 + 1 小于 1,结果为0;3 + 1 等于 4,!(4) 为 0,所以结果为 0

'a' - 'b' && 'c':'a' - 'b' 的值为 -1,不等于 0,为真;'c' 的值也不为 0,所以结果为 1

短路求值:

短路求值又称最小化求值,是一种逻辑运算符的求值策略

#include <stdio.h>

int main()
{
int a = 3, b = 3;
(a = 4) && (b = 5);
printf("a 的值为 %d ,b 的值为 %d\n", a, b);
(a = 1) || (b = 5);
printf("a 的值为 %d, b 的值为 %d\n", a, b);
return 0;
}

运行结果

#include <stdio.h>

int main()
{
int a = 3, b = 3;
(a = 0) && (b = 5);
printf("a 的值为 %d ,b 的值为 %d\n", a, b);
(a = 1) || (b = 5);
printf("a 的值为 %d, b 的值为 %d\n", a, b);
return 0;
}

运行结果

逻辑与运算进行短路求值时:

先对 && 左边的表达式进行运算,如果左边运算的结果不等于 0 的话,将对 && 右边的表达式进行运算

如果 && 左边运算的结果等于 0 的话,就不对右边的表达式进行运算

逻辑或运算进行短路求值时:

无论 || 左边的表达式的值是否为 0,都会对 || 右边的表达式进行求值

最新文章

  1. Socket.IO聊天室~简单实用
  2. 字符串流stringstream(头文件sstream)
  3. 微信sdk分享,苹果手机分享到qq好友和qq空间没有反应
  4. Flask + Gunicorn + Nginx 部署
  5. 【学习笔记】【C语言】位运算
  6. 转 intent常用功能
  7. .NET 认识
  8. &lt;script type=&quot;text/html&quot;&gt;&lt;/script&gt; js模版使用
  9. 本机安装mysql服务,步骤教程(另附SQLyog和Navicat工具)
  10. 【转】Header Only Library的介绍
  11. JVM学习笔记五:虚拟机类加载机制
  12. HTML5 input date属性引起的探索——My97DatePicker(日期选择插件)
  13. Hadoop yarn任务调度策略介绍(转)
  14. [蓝桥杯]PREV-12.历届试题_危险系数
  15. ads出现村田电容电感无法仿真的问题解决(`BJT1&#39; is an instance of an undefined model `BJTM1&#39;)
  16. delphi 控件集
  17. WebAPI——自动生成帮助文档
  18. linux上pem格式私钥转pfx格式证书的命令
  19. Introduction To Machine Learning Self-Evaluation Test
  20. folly无锁队列,尝试添加新的函数(续)

热门文章

  1. node.js 之爬虫
  2. 用sublime server 启动本地服务器(手机访问电脑页面)
  3. Failed to instantiate the default view controller for UIMainStoryboardFile &#39;Main&#39; - perhaps the designated entry point is not set?
  4. 【Python爬虫学习笔记(2)】正则表达式(re模块)相关知识点总结
  5. Java 堆和栈 垃圾回收 2015/9/16
  6. Java [Leetcode 384]Shuffle an Array
  7. Git-Svn 建立工作目录
  8. 每天一个linux命令(权限):【转载】 /etc/group文件详解
  9. 理解 Roslyn 中的红绿树(Red-Green Trees)
  10. cocos2d js jsb XMLHttpRequest 中文乱码