In depth analysis of C language variable types

  • 2020-05-26 09:47:33
  • OfStack

C is a strongly typed language. You must declare the type of a variable when you define it, and you can only assign values to variables of the same type.

1. The type of a variable tells the compiler what to do with the variable's data.

Although the c language is a strongly typed language, variables of different types can also be assigned through type conversion, and even pointer variables can be converted to int type and to char type. Essentially, the variable type just tells the compiler what to do with it, so different variables can be assigned by showing the type conversion. Understanding this is important for us to understand the transformation of the pointer. For example,


int a = 10; 
int **ptr = &a; 
int b = (int)(*ptr); // *ptr is 1 Pointer, but by converting to int , we can assign it to b .  

If you don't understand the nature of variable types, you will think that line 3 is wrong. Why is this possible? (*ptr) is a pointer, but a pointer also has a value, and its value is an address, which is essentially an unsigned integer. So we type it into int, and the data in memory of this variable doesn't change, just the parsing of it. If it is a pointer type, then the data is parsed as a pointer. If it is of type int, then the data is parsed as int. In fact, we can assign it to the char type. Convert it to char, then it will be parsed as char type. Only 1 byte of the data will be parsed into char type and assigned to ch.


char ch = (char)(*ptr); //  Some compilers will report an error and change it to (char)(int)(*ptr) You can fix it. 

2. The type of the variable tells the compiler how much memory space to allocate.

When you define a variable, the variable type tells the compiler how much memory space to allocate to store the variable.


char ch; // 1B 
int  i;  // 4B 
long l;  // 4B 
float f; // 4B 
double; // 8B 

By the way, how to understand multiple levels of Pointers. For example int * * ptr;

When we encounter a level 2 pointer, a level 3 pointer, we always don't understand what the level 3 pointer means. There is one method that is easier to understand by using multiple levels of Pointers as arrays. Level 1 Pointers are 1-dimensional arrays, level 2 Pointers are 2-dimensional arrays, level 3 Pointers are 3-dimensional arrays, and so on. Of course, sometimes we can't understand it this way, but we need to analyze it in detail.


int *ptr1;   // 1 Dimensional array  
int **ptr2; // 2 Dimensional array  
int ***ptr3; // 3 Dimensional array  

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: