C中的复合关系运算符 [英] Compound relational operators in C

查看:85
本文介绍了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屋!

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