|
||||||
const is a keyword that is used together with a variable. It makes the variable a constant value. It means that the variable declaried with const keyword cannot be changed afterwards. Actuaually the statement 'It makes the variable a constant value' would make you confused. When we say 'variable', it implies that it would be changed anytime, but the variable declaired with const keyword cannot be changed. This would be confusing to many people. I understand it might be confusing, but just take it as it is. It is the way it is implemented. Putting it more of programming jargon, 'const' is the keyword which is used to make variables immutable after their declaration. The word "immutable" refers to an object or variable that, once created or initialized, cannot be changed. If an object is immutable, any modification to it would actually create a new object rather than altering the existing one. This is common with certain data types in programming languages where immutability helps to ensure data integrity and predictability of behavior throughout the code.
const and #define in C/C++ serve similar roles in defining constants but differ fundamentally in their implementation and behavior: Essentially, const offers type safety, scope limitations, and memory allocation, while #define offers broader, unscoped text replacement without type safety or memory considerations.
Let's take a look at a simple example showing the implication of 'const' keyword. This example shows how to declare a variable as const, meaning its value cannot be changed after it is initialized. It also illustrates what happens if there is an attempt to modify a const variable, typically leading to a compiler error, thereby enforcing the immutability of the variable.
In case of value type variable, behavior of 'const' is pretty straightforward. However, if the const is used with pointer type (e.g, char *) it gets much more complicated. Take a look at following example. This is the famous strcpy function provided by C library. As you see here, _Dest is defined as 'char *' but _Source is defined as 'const char *'. This mean that the _Dest value would be changed but _Source value will not be changed within the strcpy() function. It make sence if you consider what ctrcpy() does. char * __cdecl strcpy(char * __restrict__ _Dest,const char * __restrict__ _Source); Now let's take following example and see how it works.
Let's create a function in two different way as shown below and see what happens. This shows how declaring function parameters as const prevents the function from modifying the input arguments. This usage ensures that the original data passed to the function remains unchanged, offering a safeguard against unintended side effects within the function.
|
||||||