# 2.7 类型转换

Type Conversions

我们为什么需要类型转换？

<figure><img src="https://labspc.com/wp-content/uploads/2024/01/1705658055-word-image-288-1.png" alt=""><figcaption></figcaption></figure>

\<ctype.h> 定义了一系列函数

如果要在 char 类型的变量中存储非字符数据，最好指定 signed 或 unsigned 限定符。

隐式类型转换，会有一些非正式的规则。 要注意，当表达式中包含 unsigned 类型操作数时，转换规则要复杂一些。主要原因在于，带符号值与无无符号值之间的比较运算是与机器相关的，因为它们取决于机器中不同整型类型的大小。

在任何表达式中都可以使用一个强制类型转换的一元运算符强制进行显式类型转换。

<figure><img src="https://labspc.com/wp-content/uploads/2024/01/1705658057-word-image-288-2.png" alt=""><figcaption></figcaption></figure>

{% code title="2.7.1 unsigned-forced.c" lineNumbers="true" %}

```c
int main() {
    unsigned u1 = (unsigned)-1; // 将-1 强制类型转换为无符号整数
    unsigned u2 = (unsigned)-2; // 将-1 强制类型转换为无符号整数
    unsigned u3 = ((unsigned)1)<< 32; //// 先将 1 转换为无符号整数再左移
    
    unsigned u4 = (unsigned)1; //// 
    unsigned u5 = (unsigned)0; ////
    unsigned u6 = ((unsigned)1)<< 31; //// 最小
    printf("%u\n%u\n%u\n%u\n%u\n%u\n", u1, u2, u3,u4,u5, u6); // 使用 %u 打印无符号整数
    return 0;
}
```

{% endcode %}

更多有关类型转换的知识，会在更以后去学习。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://labspc.gitbook.io/cnippets/chap2.-lei-xing-yun-suan-fu-yu-biao-da-shi/2.7-lei-xing-zhuan-huan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
