View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
c tutorial

Explore C Tutorials: From Begi…

  • 132 Lessons
  • 22 Hours

Constants in C

Updated on 05/02/20253,081 Views

In C, constants are values that remain unchanged throughout program execution. For example, the value of PI (3.14159) is constant in mathematical calculations. 

These values represent data that remains constant, such as mathematical constants or predefined settings.  

In this guide, you’ll explore the various types of constants in C with examples, focusing on how each type can be utilized in real-world scenarios. By the end of this, you’ll be able to write clean and efficient code. 

Let’s dive into the details!

Boost your C programming skills with our Software Development courses — take the next step in your learning journey! 

How to Define a Constant in C?

In C programming, constants are defined values that remain unchanged throughout the program. 

There are two primary ways to define constants: using the const keyword and the #define preprocessor directive. 

const is ideal for type-safe, modifiable constants at runtime, while #define is better for preprocessor-based, non-type-safe constants used at compile-time.

Let's explore both methods in detail.

1. Using the const Keyword

The const keyword is used to define a constant variable. When you define a constant using const, the value of the constant cannot be altered throughout the program. 

The syntax is simple and helps define constant variables with a specific data type

#include <stdio.h>
int main() {
    const int maxUsers = 100;  // Define a constant using 'const'
    printf("The maximum number of users is: %d\n", maxUsers);
    // maxUsers = 200;  // Uncommenting this will cause a compile-time error
    return 0;
}

Output: 

The maximum number of users is: 100

Explanation:

  • const int maxUsers = 100; defines a constant integer maxUsers.
  • The value of maxUsers cannot be changed once it’s defined. Trying to assign a new value to maxUsers (like maxUsers = 200;) will result in a compile-time error.
  • This method provides type safety, as you can define constants with specific types such as int, float, or char.

2. Using #define Preprocessor

The #define preprocessor directive allows you to define constants without specifying a data type. This method simply replaces all instances of the constant with the value during the preprocessing stage, before compilation

It’s commonly used for defining constant values such as mathematical constants, configuration values, or flags. 

#include <stdio.h>
#define MAX_USERS 100  // Define a constant using '#define'
int main() {
    printf("The maximum number of users is: %d\n", MAX_USERS);
    // MAX_USERS = 200;  // Uncommenting this will cause a compile-time error
    return 0;
}

Output: 

The maximum number of users is: 100

Explanation:

  • #define MAX_USERS 100; defines a constant MAX_USERS with the value 100.
  • Unlike const, #define doesn't assign a type to the constant, and the value is substituted at compile-time wherever MAX_USERS is used.
  • This method is often used for simple constants like configuration settings but does not provide type safety like the const keyword.

On that note, let's move forward and explore the types of constants in C with examples.

Types of Constants in C

Constants in C come in various forms, each serving a different purpose. Below, we'll go over each of the constant types, their declaration rules, and examples for better understanding.

1. Integer Constant

An integer constant is a constant that represents whole numbers. It can be positive, negative, or zero.

Rules:

  • It must not contain decimal points.
  • Can be represented in decimal, octal, or hexadecimal notation.
  • Examples: 100, -42, 0x1F.

Syntax: 

#include <stdio.h>
int main() {
    const int num = 42;
    printf("Integer constant: %d\n", num);
    return 0;
}

Output: 

Integer constant: 42

2. Character Constant

A character constant represents a single character enclosed in single quotes.

Rules:

  • It represents a single character or escape sequence like '\n', '\t'.
  • It is stored as an integer in memory according to the ASCII value of the character.

Syntax: 

#include <stdio.h>
int main() {
    const char letter = 'A';
    printf("Character constant: %c\n", letter);
    return 0;
}

Output: 

Character constant: A

3. Floating Point Constant

A floating-point constant represents numbers with fractional values. It is typically used for decimal points.

Rules:

  • Represented with a decimal point or in scientific notation.
  • Can be positive or negative.
  • Examples: 3.14, -0.005, 1.23e4.

Syntax: 

#include <stdio.h>
int main() {
    const float pi = 3.14f;
    printf("Floating-point constant: %.2f\n", pi);
    return 0;
}

Output: 

Floating-point constant: 3.14

4. Double Precision Floating Point Constant

This type of constant holds a larger precision value compared to the regular floating-point constant.

Rules:

  • Used when higher precision is required.
  • Declared with the double keyword.
  • Examples: 3.14159265359, 2.71828182845.

Syntax: 

#include <stdio.h>
int main() {
    const double pi = 3.14159265359;
    printf("Double precision constant: %.12f\n", pi);
    return 0;
}

Output: 

Double precision constant: 3.141592653590

5. Array Constant

An array constant in C is an array whose elements are predefined and cannot be modified after initialization. 

Typically declared using the const keyword, it stores multiple constants of the same type, ensuring that the values remain fixed throughout the program.

Rules:

  • Used to store multiple constants of the same type.
  • Cannot modify its elements after initialization.
  • It helps in maintaining the integrity of data in applications that require fixed values.

Syntax: 

#include <stdio.h>
int main() {
    const int arr[] = {1, 2, 3, 4};
    printf("Array constant: %d, %d\n", arr[0], arr[1]);
    return 0;
}

Output: 

Array constant: 1, 2

Also Read: What is Array in C? With Examples

6. Structure Constant

A structure constant represents a structured collection of different data types.

Rules:

  • It can contain various data types in one structure.
  • Cannot modify the members of the structure once initialized.

Syntax: 

#include <stdio.h>
struct Person {
    const char name[30];
    const int age;
};
int main() {
    const struct Person person1 = {"Parth", 45};
    printf("Structure constant: Name: %s, Age: %d\n", person1.name, person1.age);
    return 0;
}

Output: 

Structure constant: Name: Parth, Age: 45

Also Read: Data Types in C and C++ Explained for Beginners

Now that you understand the types of constants, let's explore how they differ from literals. 

Difference Between Constants and Literals

In C programming, a literal refers to a constant value that appears directly in the source code. For example, when you write int x = 10;, the number 10 is a literal. 

Literals are directly used in expressions or assigned to variables, and they don’t require any additional declaration.

While constants and literals might seem similar at first glance, understanding their distinctions will help you use them effectively. 

The table below outlines these differences:

Aspect

Constant

Literal

Definition

A fixed value that is declared and cannot be modified after initialization.

A value that directly appears in the code without being assigned to a variable.

Memory Allocation

Constants are stored in memory with a specific name.

Literals are not stored; they are used directly in expressions.

Declaration

Constants are declared using const or #define.

Literals are written directly in the code without any declaration.

Use

Constants can be used like variables but cannot change their value.

Literals are used directly in code and cannot be modified.

Example

const int MAX_SIZE = 100;

printf("%d", 5);

Next, let's explore what happens when you attempt to change the value of a constant. 

Changing Value of Constants in C

Constants in C are immutable values that remain unchanged throughout the program's execution. 

  • Constants ensure data integrity and prevent accidental changes to important values, like configuration settings. Although, it does not protect against indirect modification via pointers. 
  • Attempting to modify a constant violates immutability, potentially causing bugs or unpredictable behavior.
  • The compiler protects constants by placing them in read-only memory sections to prevent modification. Although some compilers store constants in read-only memory, others may not. 

What Happens If You Try to Change a Constant:

Trying to change a constant’s value results in a compile-time error to maintain its integrity.

For example, if you try to reassign a value to a constant like this: 

const int maxValue = 100;
maxValue = 200;  // Error: Cannot change the value of a constant

You will get an error message from the compiler, such as: 

error: assignment of read-only variable 'maxValue'

This error prevents unexpected changes, ensuring program stability.

How Well Do You Know Constants in C? 10 MCQs

This quiz will test your knowledge of constants in C programming. From the basics to more complex concepts, let's see how well you truly understand the use and applications of constants in C!

1. Which of the following is the correct way to define a constant in C?

A) constant int x = 10;

B) const int x = 10;

C) int const x = 10;

D) x = 10; const int

2. What will happen if you attempt to modify the value of a constant variable in C?

A) The program will print an error message

B) The program will compile, but the value won't change

C) The program will result in a runtime error

D) The compiler will generate an error message

3. Which of the following keywords is used to define a constant in C?

A) fixed

B) constant

C) const

D) static

4. What is the scope of a constant defined using the #define directive in C?

A) It is local to the function where it is defined

B) It is global to the entire program

C) It is only available in header files

D) It is available only within the file it is defined in

5. What is the output of the following code snippet?

#define PI 3.14  
int main() {
printf("%f", PI);
return 0;
}

A) It will print 3.14

B) It will print an error

C) It will print PI

D) It will print 0

6. Which of the following defines a constant that can be used in all files included in a C project?

A) const

B) #define

C) static const

D) extern const

7. What is the main difference between const and #define in C?

A) const is a keyword, while #define is a preprocessor directive

B) const can be used for variables, but #define cannot

C) #define creates variables, while const does not

D) There is no difference; they function the same

8. How can constants improve the maintainability of C code?

A) By improving runtime performance

B) By making the code more readable and easier to update

C) By increasing memory usage

D) By removing the need for loops

9. What is the purpose of the const keyword when used in function parameters?

A) It prevents the function from returning a value

B) It ensures the function doesn't modify the value of the passed parameter

C) It makes the function parameter static

D) It allows the parameter to be shared across multiple functions

10. Can a constant pointer to a variable be declared in C?

A) No, pointers cannot be constants

B) Yes, by using const int* ptr = &x;

C) Yes, but only with #define

D) Yes, by using int* const ptr = &x;

Understanding constants is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.

How Can upGrad Help You Master C Programming?

upGrad offers structured courses that will help you master the concepts of constants and other essential elements of C programming. From using const to working with #define directives, these courses will equip you with the skills needed for efficient C programming, optimizing both your problem-solving abilities and your coding expertise.

Explore upGrad’s in-depth courses to sharpen your C programming skills:

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today! 

Similar Reads:

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Addition of Two Numbers in C: A Comprehensive Guide to C Programming

String Anagram Program in C

C Program to check Armstrong Number

Binary Search in C

Find Out About Data Structures in C and How to Use Them?

C Program to Convert Decimal to Binary

FAQs

1. What are the different types of constants in C?

The types of constants in C include integer constants, character constants, floating-point constants, and string constants, each with distinct syntax and rules.

2. How can I define a constant in C?

You can define constants in C using the const keyword or the #define preprocessor directive, depending on your needs.

3. What is the difference between the const keyword and #define for defining constants?

The const keyword creates typed constants that the compiler enforces, while #define is a preprocessor macro, not checked by the compiler.

4. Can constants in C be changed during program execution?

No, constants in C are immutable. Attempting to modify them results in a compile-time error, maintaining data integrity.

5. How does the const keyword work for defining constants in C with examples?

The const keyword ensures that once a constant is defined, its value cannot be modified. Example: const int maxValue = 100;.

6. What is the role of constants in memory management in C?

Constants in C are often placed in read-only memory segments to prevent modification, helping optimize memory usage and ensuring data integrity.

7. How are string constants defined in C?

String constants in C are defined by enclosing a sequence of characters in double quotes. Example: const char* str = "Hello";.

8. Why are constants used in C programming?

Constants provide safety and clarity in programs by ensuring values remain unchanged, preventing bugs caused by accidental value changes.

9. Can #define be used for non-numeric constants?

Yes, #define can be used for any constant, including string and character constants, in C programming.

10. Are constants in C more efficient than variables?

Yes, constants in C are generally more efficient as they are optimized by the compiler and prevent unnecessary memory allocation or re-assignment.

11. How do constants affect the performance of a C program?

Constants help in optimizing the code by ensuring that fixed values are stored efficiently and avoid unnecessary memory usage during execution.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.