什么是C中的逻辑运算符的意义呢? [英] What is the point of the logical operators in C?

查看:149
本文介绍了什么是C中的逻辑运算符的意义呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有在C异或逻辑运算符(像&功放;&安培;对于要不是XOR)。我知道我可以拆分成XOR与运算,穷人和ORS,但一个简单的XOR会好得多。然后,它发生,我认为如果我用两个条件之间的正常XOR位运算符,它可能只是工作。而对于我的测试中,它做到了。

I was just wondering if there is an XOR logical operator in C (something like && for AND but for XOR). I know I can split an XOR into ANDs, NOTs and ORs but a simple XOR would be much better. Then it occurred to me that if I use the normal XOR bitwise operator between two conditions, it might just work. And for my tests it did.

考虑:

int i = 3;
int j = 7;
int k = 8;

就为了这个相当愚蠢的例子来说,如果我需要的 K 的是不是比的 I 的大于或更高的Ĵ的但不两者,XOR将是相当方便的。

Just for the sake of this rather stupid example, if I need k to be either greater than i or greater than j but not both, XOR would be quite handy.

if ((k > i) XOR (k > j))
   printf("Valid");
else
   printf("Invalid");

printf("%s",((k > i) XOR (k > j)) ? "Valid" : "Invalid");

我把按位异或的 ^ 的,它生产的无效。将两个比较的结果在两个整数导致2整数含有1,因此,异或产生的错误的。我再与&放试了一下;和|位运算符和俩给了预期的效果。这一切都有道理知道真实情况有一个非零值,而假的条件是零值。

I put the bitwise XOR ^ and it produced "Invalid". Putting the results of the two comparisons in two integers resulted in the 2 integers to contain a 1, hence the XOR produced a false. I've then tried it with the & and | bitwise operators and both gave the expected results. All this makes sense knowing that true conditions have a non zero value, whilst false conditions have zero values.

我想知道,有没有理由使用逻辑放大器;&安培;和||当位运算符&放;, |和^工作是一样的?

I was wondering, is there a reason to use the logical && and || when the bitwise operators &, | and ^ work just the same?

推荐答案

您不需要逻辑XOR,我已经忘记了SO问题,但它是类似于你在想什么,基本上我们不需要XOR,它等同于!= 反正

You don't need logical XOR, I have forgotten the SO question, but it's similar to what you're thinking, basically we don't need XOR, it's equivalent to != anyway

FALSE XOR FALSE == FALSE
FALSE XOR TRUE == TRUE
TRUE XOR FALSE == TRUE
TRUE XOR TRUE == FALSE


FALSE != FALSE == FALSE
FALSE != TRUE == TRUE
TRUE != FALSE == TRUE
TRUE != TRUE == FALSE

我要搜索我的最爱,并粘贴在这里的链接后...

I'll search my favorites, and paste here the link later...

这篇关于什么是C中的逻辑运算符的意义呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆