
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
How to modify a const variable in C?
In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization. In this section we will see how to change the value of some constant variables.
If we want to change the value of constant variable, it will generate compile time error. Please check the following code to get the better idea.
Example
#include <stdio.h> main() { const int x = 10; //define constant int printf("x = %d
", x); x = 15; //trying to update constant value printf("x = %d
", x); }
Output
[Error] assignment of read-only variable 'x'
So this is generating an error. Now we will see how we can change the value of x (which is a constant variable).
To change the value of x, we can use pointers. One pointer will point the x. Now using pointer if we update it, it will not generate any error.
Example
#include <stdio.h> main() { const int x = 10; //define constant int int *ptr; printf("x = %d
", x); ptr = &x; //ptr points the variable x *ptr = 15; //Updating through pointer printf("x = %d
", x); }
Output
x = 10 x = 15
- Related Articles
- How to initialize const member variable in a C++ class?
- Can a C++ variable be both const and volatile?
- Difference between const int*, const int * const, and int const * in C/C++?
- Difference between const int*, const int * const, and int const * in C
- Difference between const char* p, char * const p, and const char * const p in C
- Declare a const array in C#
- Variable defined with a reserved word const can be changed - JavaScript?
- How to convert a std::string to const char* or char* in C++?
- Const Qualifier in C
- Const cast in C++
- How to initialize a const field in constructor?
- How to declare a variable in C++?
- How to define a variable in C++?
- Const member functions in C++
- How to print a variable name in C?

Advertisements