C 中的复合关系运算符 [英] Compound relational operators in C
问题描述
我正在尝试将一段伪代码转换为 C 代码,并且我有类似
I am trying to convert a piece of pseudo code into a C code and I have conditions like
if (-4 <= X <=8)
THEN {Do Something}
else
{Do something else}
if 语句中的语法是否有效?可以在逻辑条件中的变量前放一个常量来检查真值吗?
Is the syntax in if statement valid? Can a constant be placed before the variable in the logical condition to check the truth value?
推荐答案
是的,您可以将常量作为 C 中逻辑检查的左侧参数.
Yes you can have constants as the left hand argument of a logical check in C.
但是,您列出的伪代码需要拆分为两个表达式:
However the pseudocode you have listed would need to be split into two expressions:
if ((-1 <= X) && (X <= 8))
旁注:许多开发人员更喜欢左侧常量"样式的逻辑语句,因为它会在某些容易出错的比较中导致编译错误.例如:假设您想计算 if (X == 3)
但不小心输入了 if (X = 3)
.后者是一个完全有效的 C 表达式,因为赋值操作返回 True.如果您要使用左侧常量"样式:if (3 = X)
会导致编译错误,从而节省大量时间.
Side Note:
Many developers prefer the "constant on the left" style of logical statement because it will cause a compilation error in certain error-prone comparisons. For example:
Let's say you wanted to evaluate if (X == 3)
but accidentally typed if (X = 3)
.
The latter is a perfectly valid C expression because the assignment operation returns True.
If you were to use the "constant on the left" style:
if (3 = X)
would cause a compilation error, thus save a lot of time.
这篇关于C 中的复合关系运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!