C 语言的类型转换

文章目录

  • 自动类型转换
  • 强制类型转换

自动类型转换

Statements and expressions should normally use variables and constants of just one type. If, however, you mix types, C doesn’t stop dead in its tracks the way, say, Pascal does. Instead, it uses a set of rules to make type conversions automatically. This can be a convenience, but it can also be a danger, especially if you are mixing types inadvertently.

It is a good idea to have at least some knowledge of the type conversion rules.

The basic rules are

  1. When appearing in an expression, char and short , both signed and unsigned , are automatically converted to int or, if necessary, to unsigned int . (If short is the same size as int , unsigned short is larger than int ; in that case, unsigned short is converted to unsigned int .) Under K&R C, but not under current C, float is automatically converted to double . Because they are conversions to larger types, they are called promotions.
  2. In any operation involving two types, both values are converted to the higher ranking of the two types.
  3. The ranking of types, from highest to lowest, is long double , double , float , unsigned long long , long long , unsigned long , long , unsigned int , and int . One possible exception is when long and int are the same size, in which case unsigned int outranks long . The short and char types don’t appear in this list because they would have been already promoted to int or perhaps unsigned int.
  4. In an assignment statement, the final result of the calculations is converted to the type of the variable being assigned a value. This process can result in promotion, as described in rule 1, or demotion , in which a value is converted to a lower-ranking type.
  5. When passed as function arguments, char and short are converted to int , and float is converted to double . This automatic promotion is overridden by function prototyping.

Promotion is usually a smooth, uneventful process, but demotion can lead to real trouble. The reason is simple: The lower-ranking type may not be big enough to hold the complete number. For instance, an 8-bit char variable can hold the integer 101 but not the integer 22334.

What happens when the converted value won’t fit into the destination? The answer depends on the types involved. Here are the rules for when the assigned value doesn’t fit into the destination type:

  1. When the destination is some form of unsigned integer and the assigned value is an integer, the extra bits that make the value too big are ignored. For instance, if the destination is 8-bit unsigned char , the assigned value is the original value modulus 256.
  2. If the destination type is a signed integer and the assigned value is an integer, the result is implementation-dependent.
  3. If the destination type is an integer and the assigned value is floating point, the behavior is undefined. What if a floating-point value will fit into an integer type? When floating types are demoted to integer types, they are truncated, or rounded toward zero. That means 23.12 and 23.99 both are truncated to 23 and that -23.5 is truncated to -23.

代码示例:

#include<stdio.h>
int main(void)
{char ch;int i;float fl;ch = i = fl = 'C';printf("ch = %c, i = %d, fl = %2.2f\n", ch, i, fl);return 0;
}

结果:

ch = C, i = 67, fl = 67.00

分析:

这里, 字符 ‘C’ 作为一字节的 ASCII 值, 储存在 ch 中.

整数变量 i 接受由字符 ‘C’ 转换而来的整数, 即 67, 然后按照 4 字节储存 67.

浮点型变量 fl 接受由字符 ‘C’ 转换而来的整数, 即 67, 再将 67 转换为浮点数, 67.00.

程序示例:

#include<stdio.h>
int main(void)
{char ch;ch = 'C' + 1;printf("ch = %c\n", ch);return 0;
}
ch = D

分析:

字符 ‘C’ 转换成整数, 即 67, 然后加 1. 计算结果是四字节的整数 68, 然后被截断成 1 字节的整数 68, 储存在字符型变量 ch 中, 根据转换说明 %c 进行打印时, 68 被解释成 ‘D’ 的 ASCII 码值. 于是打印字符 D.

程序示例:

#include<stdio.h>
int main(void)
{char ch = 'A';int i;float fl = 2.0f;printf("字母 A 的 ASCII 码是:%d\n", ch);i = fl + ch * 2;printf("i = %d\n", i);return 0;
}

结果:

字母 A 的 ASCII 码是:65
i = 132

分析:

语句 i = fl + ch * 2; 中, ch 为了和 2 相乘, 需要先转换为 4 位的 int 型的 65, 得到计算结果为 4 位的 int 型的 130.

4 位的 int 型的 130 为了和 float 类型的 fl 相加, 需要先转换为 float 类型, 即 130f.

变成了 130.0f + 2.0f , 得到结果为 132.0f.

要把 132.0f 赋值给 int 类型的 i, 需要把 132.0f 转变为 4 位的 int 类型的 132, 储存在 int 类型的 i 中.

程序示例:

#include<stdio.h>
int main(void)
{char ch = 1107;printf("%c\n", ch);printf("%d\n", 1107 % 256);printf("%c\n", 1107 % 256);return 0;
}

结果:

S
83
S

分析:

这里显示了降级的过程.

把 ch 设置为超出其范围的一个值, 忽略额外的位, 按照上述的规则, 相当于将这个值对 265 求模.

程序示例:

#include<stdio.h>
int main(void)
{char ch = 87.56;printf("%d\n", ch);printf("%c\n", ch);printf("%c\n", 87);return 0;
}

结果:

87
W
W

分析:

演示了另一个截断的例子. 这里将一个 float 值赋给了 char 类型变量, 丢弃了小数点后面的数字.

强制类型转换

应该尽量避免自动类型转换, 尤其是降级.

有时需要进行精确的类型转换, 或者明确指明类型转换的意图.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/24547.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux修改系统语言

sudo dpkg-reconfigure locales 按pagedown键&#xff0c;移动红色光标到 zh_CN.UTF-8 UTF-8&#xff0c;空格标记*号&#xff08;没标记下一页没有这一项&#xff09;&#xff0c;回车。 下一页选择 zh_CN.UTF-8。 如果找不到 dpkg-reconfigure whereis dpkg-reconfigure …

HTML 初

前言 HTML的基本骨架 HTML基本骨架是构建网页的最基本的结果。 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0">…

iOS——Block回调

先跟着我实现最简单的 Block 回调传参的使用&#xff0c;如果你能举一反三&#xff0c;基本上可以满足了 OC 中的开发需求。已经实现的同学可以跳到下一节。 首先解释一下我们例子要实现什么功能&#xff08;其实是烂大街又最形象的例子&#xff09;&#xff1a; 有两个视图控…

【Linux操作系统】深入理解Linux磁盘分区和挂载

Linux磁盘分区和挂载是系统管理中非常重要的一部分&#xff0c;它们可以帮助我们更好地管理存储空间和文件系统。本文将详细介绍Linux磁盘分区和挂载的概念、原理以及实践操作&#xff0c;并提供相应的例子、代码和指令&#xff0c;帮助读者全面了解和掌握这两个关键概念。 文章…

互感和励磁电感(激磁电感)的关系

互感器&#xff0c;变压器&#xff0c;他们之间有着千丝万缕的联系&#xff0c;自感&#xff0c;互感&#xff0c;激磁电感&#xff0c;漏感、耦合系数、理想互感器、理想变压器&#xff0c;这些东西的概念理解和相互之间的关系式。都搞明白了吗&#xff1f;

vim怎么使用,vim使用教程,vimtutor怎么切换中文 汉化

vim 使用 在安装了 vim 的 unix 系统下可以使用 vimtutor zh_cn 开启下面的教程 序言 欢 迎 阅 读 《 V I M 教 程 》 —— 版本 1.7 Vim 是一个具有很多命令的功能非常强大的编辑器。限于篇幅&#xff0c;在本教程当中就不详细介绍了。本教程的…

elasticsearch 将时间类型为时间戳保存格式的时间字段格式化返回

dsl查询用法如下&#xff1a; GET /your_index/_search {"_source": {"includes": ["timestamp", // Include the timestamp field in the search results// Other fields you want to include],"excludes": []},"query": …

外国机构在中国境内提供金融信息服务23家许可名单

6月30日&#xff0c;国家互联网信息办公室公布23家外国&#xff08;境外&#xff09;机构在中国境内提供金融信息服务许可名单&#xff0c;如下&#xff1a;

LeetCode643. 子数组最大平均数 I

题干 给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。 请你找出平均数最大且 长度为 k 的连续子数组&#xff0c;并输出该最大平均数。 任何误差小于 10^-5 的答案都将被视为正确答案。 示例1&#xff1a; 输入&#xff1a;nums [1,12,-5,-6,50,3], k 4 输出&am…

前端小练习:案例4.3D图片旋转展示(旋转木马)

一.效果预览图 二.实现思路 1.实现旋转木马效果的第一步是先准备好自己需要的图片&#xff0c;创建html文件 2.旋转木马的实现&#xff0c;关键点在3D形变和关键帧动画。 3.步骤&#xff0c;定义一个div使其居中&#xff0c;&#xff0c;把图片放进div盒子里&#xff0c;因为图…

Vue系列第七篇:Element UI之el-main,el-table,el-dialog,el-pagination,el-breadcrumb等控件使用

本篇实现主页面功能&#xff0c;包括主页面排版布局&#xff0c;学生管理模块实现&#xff0c;后台接口实现等功能。 目录 1.运行效果 1.1登录页面 1.2主页面 1.3学生管理 - 信息列表 1.4学生管理 - 信息管理 1.5学生管理 - 作业列表 1.6学生管理 - 作业管理 2.前端代码…

统计方形(c++题解)

题目背景 1997年普及组第一题 题目描述 有一个 nm 方格的棋盘&#xff0c;求其方格包含多少正方形、长方形&#xff08;不包含正方形&#xff09;。 输入格式 一行&#xff0c;两个正整数 n,m&#xff08;n≤5000,m≤5000&#xff09;。 输出格式 一行&#xff0c;两个正…

npm install时出现的问题Failed at the node-sass@4.14.1 postinstall script

从阿里云上拉取下来项目后&#xff0c;首先使用npm install 命令进行安装所需依赖&#xff0c;意想不到的事情发生了&#xff0c;报出了Failed at the node-sass4.14.1 postinstall script&#xff0c;这个问题&#xff0c;顿时一脸懵逼&#xff1b;询问前端大佬&#xff0c;给…

危大工程智慧工地源码,微服务+Java+Spring Cloud +UniApp +MySql 物联网、人工智能、视频AI分析

一套智慧工地管理平台源码&#xff0c;PC端移动APP端可视货数据管理端源码 智慧工地可视化系统利用物联网、人工智能、云计算、大数据、移动互联网等新一代信息技术&#xff0c;通过工地中台、三维建模服务、视频AI分析服务等技术支撑&#xff0c;实现智慧工地高精度动态仿真&a…

【新人指南】给新人软件开发工程师的干货建议

在我是新人时&#xff0c;如果有前辈能够指导方向一下&#xff0c;分享一些踩坑经历&#xff0c;或许会让我少走很多弯路&#xff0c;节省更多的学习的成本。 这篇文章根据我多年的工作经验&#xff0c;给新人总结了一些建议&#xff0c;希望对你会有所帮助。 写好注释 没有注…

ELFK——ELK结合filebeat日志分析系统(2)

目录 一、filebeat 二、ELFK 1.原理简介 2.在ELK基础上部署filebeat 一、filebeat Filebeat&#xff0c;轻量级的开源日志文件数据搜集器。通常在需要采集数据的客户端安装 Filebeat&#xff0c;并指定目录与日志格式&#xff0c;Filebeat 就能快速收集数据&#xff0c;并…

解决宝塔面板升级获取更新包失败,请稍后更新或联系宝塔运维

宝塔Linux面板执行升级命令后失败&#xff0c;提示“获取更新包失败&#xff0c;请稍后更新或联系宝塔运维”如何解决&#xff1f;新手站长分享宝塔面板升级失败的解决方法&#xff1a; 宝塔面板升级失败解决方法 1、使用root账户登录到你的云服务器上&#xff0c;宝塔Linux面…

LLVM笔记1

参考&#xff1a;https://www.bilibili.com/video/BV1D84y1y73v/?share_sourcecopy_web&vd_sourcefc187607fc6ec6bbd2c74a3d0d7484cf 文章目录 零、入门名词解释1. Compiler & Interpreter2. AOT静态编译和JIT动态解释的编译方式3. Pass4. Intermediate Representatio…

基于netty的rpc远程调用

QPRC &#x1f680;&#x1f680;&#x1f680;这是一个手写RPC项目&#xff0c;用于实现远程过程调用&#xff08;RPC&#xff09;通信&#x1f680;&#x1f680;&#x1f680; 欢迎star串门&#xff1a;https://github.com/red-velet/ &#x1f680;Q-PRC 一、功能特性 …

关于HIVE的分区与分桶

1.分区 1.概念 Hive中的分区就是把一张大表的数据按照业务需要分散的存储到多个目录&#xff0c;每个目录就称为该表的一个分区。在查询时通过where子句中的表达式选择查询所需要的分区&#xff0c;这样的查询效率会提高很多 个人理解白话:按表中或者自定义的一个列,对数据进…