The Wayback Machine - https://web.archive.org/web/20241116042842/https://www.geeksforgeeks.org/constants-in-c/
Open In App

Constants in C

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the constants.

In this article, we will discuss about the constants in C programming, ways to define constants in C, types of constants in C, their properties and the difference between literals and constants.

What is a constant in C?

As the name suggests, a constant in C is a variable that cannot be modified once it is declared in the program. We can not make any change in the value of the constant variables after they are defined. If you’re interested in understanding how constants can be integrated with various data structures, the C Programming Course Online with Data Structures provides detailed explanations and use cases.

How to Define Constant in C?

We define a constant in C language using the const keyword. Also known as a const type qualifier, the const keyword is placed at the start of the variable declaration to declare that variable as a constant.

Syntax to Define Constant

const data_type var_name = value;

syntax of constants in c

Example of Constants in C

C
// C program to illustrate constant variable definition
#include <stdio.h>

int main()
{

    // defining integer constant using const keyword
    const int int_const = 25;

    // defining character constant using const keyword
    const char char_const = 'A';

    // defining float constant using const keyword
    const float float_const = 15.66;

    printf("Printing value of Integer Constant: %d\n",
           int_const);
    printf("Printing value of Character Constant: %c\n",
           char_const);
    printf("Printing value of Float Constant: %f",
           float_const);

    return 0;
}

Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000

One thing to note here is that we have to initialize the constant variables at declaration. Otherwise, the variable will store some garbage value and we won’t be able to change it. The following image describes examples of incorrect and correct variable definitions.

right way to declare constants in c

Types of Constants in C

The type of the constant is the same as the data type of the variables. Following is the list of the types of constants

  • Integer Constant
  • Character Constant
  • Floating Point Constant
  • Double Precision Floating Point Constant
  • Array Constant
  • Structure Constant

We just have to add the const keyword at the start of the variable declaration.

Properties of Constant in C

The important properties of constant variables in C defined using the const keyword are as follows:

1. Initialization with Declaration

We can only initialize the constant variable in C at the time of its declaration. Otherwise, it will store the garbage value.

2. Immutability

The constant variables in c are immutable after its definition, i.e., they can be initialized only once in the whole program. After that, we cannot modify the value stored inside that variable.

C
// C Program to demonstrate the behaviour of constant
// variable
#include <stdio.h>

int main()
{
    // declaring a constant variable
    const int var;
    // initializing constant variable var after declaration
    var = 20;

    printf("Value of var: %d", var);
    return 0;
}


Output

In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^

Difference Between Constants and Literals

The constant and literals are often confused as the same. But in C language, they are different entities and have different semantics. The following table lists the differences between the constants and literals in C:

Constant

Literals

Constants are variables that cannot be modified once declared.Literals are the fixed values that define themselves.
Constants are defined by using the const keyword in C. They store literal values in themselves.They themselves are the values that are assigned to the variables or constants.
We can determine the address of constants.We cannot determine the address of a literal except string literal.
They are lvalues.They are rvalues.
Example: const int c = 20.Example: 24,15.5, ‘a’, “Geeks”, etc.

Defining Constant using #define Preprocessor

We can also define a constant in C using #define preprocessor. The constants defined using #define are macros that behave like a constant. These constants are not handled by the compiler, they are handled by the preprocessor and are replaced by their value before compilation.

#define const_name value

Example of Constant Macro

C
// C Program to define a constant using #define
#include <stdio.h>
#define pi 3.14

int main()
{

    printf("The value of pi: %.2f", pi);
    return 0;
}

Output
The value of pi: 3.14

Note: This method for defining constant is not preferred as it may introduce bugs and make the code difficult to maintain.

FAQs on C Constants

Q1. Define C Constants.

Answer:

Constants in C are the immutable variables whose values cannot be modified once they are declared in the C program.

Q2. What is the use of the const keyword?’

Answer:

The const keyword is the qualifier that is used to declare the constant variable in C language.

Q3. Can we initialize the constant variable after the declaration?

Answer:

No, we cannot initialize the constant variable once it is declared.

Q4. What is the right way to declare the constant in C?

Answer:

The right way to declare a constant in C is to always initialize the constant variable when we declare.

Q5. What is the difference between constant defined using const qualifier and #define?

Answer:

The following table list the differences between the constants defined using const qualifier and #define in C:

Constants using constConstants using #define
They are the variables that are immutableThey are the macros that are replaced by their value.
They are handled by the compiler.They are handled by the preprocessor.
Syntax: const type name = value;Syntax: #define name value

Q6. Is there any way to change the value of a constant variable in C?

Answer:

Yes, we can take advantage of the loophole created by pointers to change the value of a variable declared as a constant in C. The below C program demonstrates how to do it.

C
// C Program to change the value of a constant variable
#include <stdio.h>

int main()
{
    // defining an integer constant
    const int var = 10;

    printf("Initial Value of Constant: %d\n", var);

    // defining a pointer to that const variable
    int* ptr
        = (int*)&var; // explicit cast to remove constness
    // changing value
    *ptr = 500;

    printf("Final Value of Constant: %d\n", var);
    printf("Accessing through pointer: %d\n", *ptr);
    return 0;
}

Output
Initial Value of Constant: 10
Final Value of Constant: 500
Accessing through pointer: 500

Related Article – Const Qualifier in C



Previous Article
Next Article

Similar Reads

Data type of character constants in C and C++
In C, data type of character constants is int, but in C++, data type of same is char. If we save below program as test.c then we get 4 as output (assuming size of integer is 4 bytes) and if we save the same program as test.cpp then we get 1(assuming size of char is 1 byte) C/C++ Code // C++ program demonstrating that data type of character // const
1 min read
Difference Between Constants and Variables in C
The constants and variables in C are both used to store data. So it is essential to know the difference between the variables and constants in C so that we can decide which one to use based on the situation. In this article, we will discuss the basic difference between a constant and a variable in C language. Variables in C A variable in simple ter
3 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Top 25 C Projects with Source Codes for 2024
If you're looking for project ideas to boost your C Programming skills, you're in the right spot. Programming is about problem-solving and adapting to ever-changing technology. Start with C, the foundation of many modern languages, to refine your programming abilities. Despite being introduced 50 years ago, C remains a top choice for beginners due
14 min read
Difference Between Call by Value and Call by Reference in C
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. The parameters passed to the function are called actual parameters whereas the parameters received by the function are called formal parameters. Call By Value in CIn call by value
5 min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library <stdio.h> and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatted_string", arguments_list);Parametersformatted_st
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
Structure of the C Program
The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and understand in a particular format. C program must follow the below-mentioned outline in order to successfully compile and execute. Debugging is easier in a well-structured C program. Sections of the C ProgramThere are 6 basic sections respo
5 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the oldest and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating system
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Prime Number Program in C
A prime number is a natural number greater than 1 and is completely divisible only by 1 and itself. In this article, we will learn how to check whether the given number is a prime number or not in C. Examples Input: n = 29Output: 29 is primeExplanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number. Input: n = 15Output:
3 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different
6 min read
Basics of File Handling in C
File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Why do we need File Handling in C?So far the operations using the
15 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Multidimensional Arrays in C - 2D and 3D Arrays
Prerequisite: Arrays in C A multi-dimensional array can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays are 2D arrays and 3D arrays. In this article, we will learn about multidimensional arrays in C programming language. Synta
10 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Socket Programming in C
What is Socket Programming?Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. State Diagram for S
5 min read
std::sort() in C++ STL
std::sort() is an STL function that is used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structure which have random access to its elements such as vectors and arrays. It is defined inside <algorithm> header file. Syntaxstd::sort (first, last, comp);Paramete
4 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
C Structures
The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type. Additionally, the values of a structure are stored i
10 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Exception Handling in C++
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code. So basica
11 min read
Article Tags :
three90RightbarBannerImg