当前位置:网站首页>020 basics of C language: C language forced type conversion and error handling
020 basics of C language: C language forced type conversion and error handling
2022-06-27 04:24:00 【Prison plan progress 50%】
List of articles
One : summary
Cast is to convert a variable from one type to another data type . for example , If you want to store one long Type value into a simple integer , You need to put long Type cast to int type . You can use the cast operator to explicitly cast a value from one type to another .(type_name) expression
example :
Use cast operators to divide one integer variable by another , Get a floating point number :
#include <stdio.h>
int main(){
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("mean: %f \n", mean);
}
result :mean: 3.400000
It should be noted here that cast operators take precedence over division , therefore sum The value of is first converted to double type , Then divide by count, Get a type of double Value .
Type conversion can be implicit , Executed automatically by the compiler , It can also be explicit , Specify by using a cast operator . In programming , Cast operators are used when type conversion is needed , Is a good programming habit .
Two : Integer promotion
Integer promotion is to put less than int or unsigned int The integer type of is converted to int or unsigned int The process of
#include <stdio.h>
int main(){
int i = 17;
char c = 'c'; // ascii The value is 99
int sum;
sum = i + c;
printf("value of sum: %d \n", sum);
}
result :value of sum: 116
ad locum ,sum The value of is 116, Because the compiler does integer Promotion , When performing an actual addition operation , hold 'c' The value of is converted to the corresponding ascii value .
3、 ... and : The usual arithmetic conversion
Implicitly cast values to the same type . The compiler first performs integer Promotion , If the operand types are different , Then they will be converted to the type of the highest level in the following levels :int --> unsigned int --> long --> unsigned long --> long long --> unsigned long long --> float --> double --> long double
Common arithmetic transformations are not applicable to assignment operators , Logical operators && and ||.
Let's take a look at the following examples to understand the concept :
#include <stdio.h>
int main()
{
int i = 17;
char c = 'c'; /* ascii The value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed , It will produce the following results :
Value of sum : 116.000000
ad locum ,c First it's converted to an integer , But because the final value is double Type , So I can use the common arithmetic conversion , The compiler will put i and c Convert to floating point , And add them up to get a floating point number .
Four : Error handling
4.1: summary
C Language does not provide direct support for error handling , But as a system programming language , It allows you to access the underlying data in the form of a return value . When something goes wrong , Most of the C or UNIX Function call returns 1 or NULL, At the same time, an error code will be set errno, The error code is a global variable , Indicates that an error occurred during a function call . You can go to <error.h> Various error codes are found in the header file .
therefore ,C The programmer can check the return value , Then decide which appropriate action to take according to the return value . Developers should be at program initialization time , hold errno Set to 0, It's a good programming habit .0 A value indicates that there are no errors in the program .
4.2:errno/perror()/strerror()
C Language provides perror() and strerror() Function to display and errno Related text messages .
perror() The function displays the string passed to it , Followed by a colon , A space and current errno The text representation of the value .
strerror() function , Return a pointer , The pointer points to the current errno The text representation of the value .
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno;
int main(){
FILE *pf;
int errnum;
pf = fopen("unexist.txt", "rb");
if(pf == NULL){
errnum = errno;
fprintf(stderr, "Value of errno: %d \n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s \n", strerror(errnum));
}else{
fclose(pf);
}
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# ./cuowuchuli
Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory
边栏推荐
- List of best reading materials for machine learning in communication
- [BJDCTF2020]The mystery of ip
- windows上安装MySQL
- 渗透测试-文件上传/下载/包含
- Nestjs environment variable configuration to solve the problem of how to inject services into interceptors
- Advanced Mathematics (Seventh Edition) Tongji University exercises 1-10 personal solutions
- 018 C语言基础:C文件读写
- WPF open source control library extended WPF toolkit Introduction (Classic)
- Cache comprehensive project - seckill architecture
- 【B站UP DR_CAN学习笔记】Kalman滤波3
猜你喜欢

【B站UP DR_CAN学习笔记】Kalman滤波3

WPF 开源控件库Extended WPF Toolkit介绍(经典)

Why does C throw exceptions when accessing null fields?

深潜Kotlin协程(十五):测试 Kotlin 协程

PostgreSQL basic command tutorial: create a new user admin to access PostgreSQL

跟着BUU学习Crypto(周更)

Fplan power planning

【B站UP DR_CAN学习笔记】Kalman滤波2

低代码开发平台NocoBase的安装
![[array]bm94 rainwater connection problem - difficult](/img/2b/1934803060d65ea9139ec489a2c5f5.png)
[array]bm94 rainwater connection problem - difficult
随机推荐
2022-06-26: what does the following golang code output? A:true; B:false; C: Compilation error. package main import “fmt“ func main() { type
math_ Number set (number set symbol) and set theory
iOS开发:对于动态库共享缓存(dyld)的了解
PostgreSQL basic command tutorial: create a new user admin to access PostgreSQL
文旅灯光秀打破时空限制,展现景区夜游魅力
Argo Workflows —— Kubernetes的工作流引擎入门
733. 图像渲染
1.5 conda的使用
Qchart note 2: add rollover display
Games101 job 7 improvement - implementation process of micro surface material
2022-06-26:以下golang代码输出什么?A:true;B:false;C:编译错误。 package main import “fmt“ func main() { type
Network structure and model principle of convolutional neural network (CNN)
Further exploration of handler (Part 2) (the most complete analysis of the core principles of handler)
Basic functions of promise [IV. promise source code]
Nestjs environment variable configuration to solve the problem of how to inject services into interceptors
Building lightweight target detection based on mobilenet-yolov4
为什么 C# 访问 null 字段会抛异常?
USB DRIVER
日志收集系統
Almost because of json Stringify lost his bonus