The differences between const and C++ in C are explained in detail
- 2020-05-17 06:05:36
- OfStack
The differences between const and C++ in C are explained in detail
Both C++ and C #define can be used to define constants. There is a difference between const which is a constant with data type and const which is not a macro constant. The compiler can perform static type safety check on the former, but only character substitution and no type safety check on the latter.
In C language, const and C++ are also quite different. In C language, the variable modified by const is still a variable, which means that this variable is read-only and cannot be changed visually. However, after modified by const, C++ becomes a constant. For example, the following code:
const int n=10;
int a[n];
These two lines of code will give you an error in C because the array length must be constant when you declare an array, whereas n is a variable in C. After the modification of C++ with const, n is already equivalent to 1 constant, so it can be passed.
Take a look at the following code:
const int a=3;
int* p=&a;
*p=4;
This is not allowed in C++, because a has become a constant after being modified with const, so it is not allowed to be modified, either by explicitly changing the value of a or by other means.
Thank you for reading, I hope to help you, thank you for your support of this site!