Example analysis of automatic implicit conversion and type casting in C language

  • 2020-04-02 02:29:40
  • OfStack

This paper makes an in-depth analysis of the attention points of automatic implicit conversion and type casting in C language through an example of C program. The details are as follows:

Let's look at a C program:


#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
double proc(int q){
int n;
double sum,t;//The key to this example is the type of these variables
sum = 2.0;
while(sum<=q){
t=sum;
//sum = sum+(n+1)/n;// Automatic implicit conversion 
sum =sum +(double)((n+1)/n);//Type cast
n++;
}
return t;
}
void main(){
system("C");
printf("%fn",proc(10))
}

Analysis:

When we see sum is equal to sum plus n plus 1 over n; Such statements always cast the variable "n" without thinking, but there is a sentence in the c language book "when a low-precision data type and a high-precision data type operation, the result is high-precision type. "Don't be confused at this time, it just emphasizes the result. In order for others to understand what we are doing with the data, it is best to cast it. In this case, the so-called automatic implicit conversion from low precision to high precision is actually a forced type conversion.


Related articles: