> For the complete documentation index, see [llms.txt](https://labspc.gitbook.io/cnippets/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://labspc.gitbook.io/cnippets/chap2.-lei-xing-yun-suan-fu-yu-biao-da-shi/2.6-guan-xi-yun-suan-fu-yu-luo-ji-yun-suan-fu.md).

# 2.6 关系运算符与逻辑运算符

### 2.6.1 关系运算符 <a href="#vavkx" id="vavkx"></a>

C语言提供了关系操作符（例如，等于、不等于、大于、小于等），用于比较变量之间的关系。这些操作符在控制流程中的条件语句中非常有用，如`if`语句和`while`循环。

关系操作：关系操作符（如等于 (`==`)、大于 (`>`)、小于 (`<`)）用于比较变量之间的关系。

```c
int x = 5;
int y = 7;
if (x < y) {
    // 条件成立，执行代码
}
```

Relational Operators（关系操作符）:

* `==` : Equal to（等于）
* `!=` : Not equal to（不等于）
* `<` : Less than（小于）
* `>` : Greater than（大于）
* `<=` : Less than or equal to（小于等于）
* `>=` : Greater than or equal to（大于等于）

### 2.6.2 逻辑运算符 <a href="#ynci0" id="ynci0"></a>

逻辑操作符（如逻辑与、逻辑或、逻辑非）用于执行逻辑运算，通常与条件语句一起使用，以便进行复杂的逻辑判断。

逻辑操作：逻辑操作符（如逻辑与 (`&&`)、逻辑或 (`||`)、逻辑非 (`!`)）用于执行逻辑运算，通常在条件语句中使用。

```c
int condition1 = 1;
int condition2 = 0;
if (condition1 && !condition2) {
    // 条件成立，执行代码
}
```

这段代码演示了逻辑操作符的使用。在这个示例中，我们有两个整数变量 `condition1` 和 `condition2`，它们分别初始化为1和0。

然后，我们使用逻辑操作符在 `if` 语句中进行条件判断：

* `&&`（逻辑与）操作符用于将两个条件连接在一起，只有当两个条件都为真时，整个表达式才为真。在这里，`condition1` 为真（非零值），`!condition2` 也为真，因为 `!` 操作符是逻辑非，它将 `condition2` 的值从0取反成1。因此，整个表达式成立，`if` 语句的代码块将被执行。 （这里 非操作!，是对condition2的值取反）

总结一下，这段代码的逻辑是：如果 `condition1` 为真且 `condition2` 为假，执行 `if` 语句中的代码块。在这个特定示例中，条件成立，因为 `condition1` 为真（1），而 `condition2` 为假（0）。这是逻辑操作符的一种常见用法，用于根据多个条件判断来控制程序的执行流程。

**Logical Operators（逻辑操作符）**:

* `&&` : Logical AND（逻辑与）
* `||` : Logical OR（逻辑或）
* `!` : Logical NOT（逻辑非）

### 2.6.3 练习题 <a href="#owa5d" id="owa5d"></a>

Exercise 2-2. Write a loop equivalent to the for loop above without using && or | |.

```c
for (i=0; i<lim-1 && (c=getchar()) !='\n' && c!=EOF; ++i) 
    s[il = c;
```
