c - 由于从 -128 到 -1 的字符与从 +128 到 +255 的字符相同,那么使用 unsigned char 有什么意义呢?

标签 c char unsigned-char

#include <stdio.h>
#include <conio.h>
int main()
{
    char a=-128;
    while(a<=-1)
    {
        printf("%c\n",a);
        a++;
    }
    getch();
    return 0;
}

上面代码的输出与下面代码的输出相同

#include <stdio.h>
#include <conio.h>
int main()
{
    unsigned char a=+128;
    while(a<=+254)
    {
        printf("%c\n",a);
        a++;
    }
    getch();
    return 0;
}

那为什么要用unsigned charsigned char呢?

最佳答案

K & R,章节和诗句,p. 43 和 44:

There is one subtle point about the conversion of characters to integers. The language does not specify whether variables of type char are signed or unsigned quantities. When a char is converted to an int, can it ever produce a negative integer? The answer varies from machine to machine, reflecting differences in architecture. On some machines, a char whose leftmost bit is 1 will be converted to a negative integer ("sign extension"). On others, a char is promoted to an int by adding zeros at the left end, and thus is always positive. [...] Arbitrary bit patterns stored in character variables may appear to be negative on some machines, yet positive on others. For portability, specify signed or unsigned if non-character data is to be stored in char variables.

关于c - 由于从 -128 到 -1 的字符与从 +128 到 +255 的字符相同,那么使用 unsigned char 有什么意义呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36147357/

相关文章:

c - 当我尝试读取 txt 文件时,fopen() 总是返回 NULL

我不能只打印一个循环吗? - C

c - 在 Linux 中使用 Signal 发送信息

C 程序在尝试使用指针访问字符串数据时不打印文本

c++如何将我的命令行参数(MAC地址)转换为无符号字符

c++ - 将 unsigned char 转换为字符串,然后再转换为 unsigned char

c - 在 C 中实现队列

java - 读取.txt文件并制作数组(java)

c++ - 为什么需要在索引中添加 '0' 才能访问数组值?

c - 警告 : left shift count >= width of type [enabled by default]