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

Constants in C: Definition, Types, and Code Examples

Updated on 03/06/20253,181 Views

Why use constants in C when you can just assign values to variables?

Because constants make your code more secure, readable, and error-proof.

Constants in C are fixed values that do not change during program execution. You can use them to represent values like pi (3.14), maximum limits, or any fixed data that should remain unchanged. C provides various types of constants—integer, floating-point, character, string, and symbolic constants defined using #define or const.

In this tutorial, you’ll learn what constants in C are, how they differ from variables, and where to use them. We’ll explain each type with syntax, examples, and best practices to avoid accidental modifications.

By the end, you’ll be comfortable using constants to write safer and cleaner C programs. Want to sharpen your skills in C programming? Explore our Software Engineering Courses for structured learning and real-world coding experience.

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.

Feeling confident with C programming? It's the perfect time to broaden your technical expertise. Consider exploring these carefully selected courses:

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.

MCQs on Constants in C

1. What is a constant in C?

a) A variable that changes during runtime

b) A value that remains fixed during program execution

c) A macro

d) A preprocessor directive

2. What is the correct syntax for declaring a constant variable?

a) const int x = 10;

b) int const x = 10;

c) define x 10;

d) Both a and b

3. What will happen if you try to modify a const variable in C?

a) It compiles and modifies it

b) It shows a warning but allows

c) Compilation error

d) It auto-declares a new variable

4. Which of the following defines a symbolic constant?

a) symbol x = 10;

b) const x = 10;

c) #define X 10

d) define const x 10

5. Which of these is not a valid type of constant in C?

a) Integer constant

b) Float constant

c) Char constant

d) Static constant

6. What is the scope of a constant declared using #define?

a) Function-level only

b) Block-level only

c) File-wide, before compilation

d) Dynamic at runtime

7. What’s the main difference between const and #define?

a) const is evaluated at compile time, #define at runtime

b) #define has a type, const doesn’t

c) const is type-safe, #define is preprocessed

d) No difference

8. What is the result of this code?

#define PI 3.14  
const float pi = 3.14;  
printf("%f %f", PI, pi);

a) 3.14 3.14  

b) Error due to duplicate values  

c) Compile error  

d) Segmentation fault

9. A student writes:  

const int x = 10;  
int* ptr = &x;  
*ptr = 20;

What is the outcome?**

a) Compilation error

b) Runtime error

c) Undefined behavior

d) Modifies x to 20

10. In an embedded C program, constants are used in #define but behave unexpectedly. What might be the issue?

a) Scope leak

b) Type safety and macro side-effects

c) Stack overflow

d) Missing header files

11. You're asked to pass a constant variable to a function without letting it modify the value. What's the correct signature?

a) void func(int x)

b) void func(const int x)

c) int func(int* x)

d) const func(int x)

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

+918068792934

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.