What Are Constants in C Language? Types, Examples, Rules, How to Use?
Introduction
What are constants in C language? How many types of constants are there in C? Why and how to use constants, and what are the rules to follow?
Let’s find answers to all these questions and more in this comprehensive write-up on constants in C language.
As part of our comprehensive C Language Tutorial for Beginners, we have already covered several important topics of this programming language, including:
So, now, it’s time to understand what is a constant in C with examples, rules, types, and everything else that you must know.
What Are Constants in C Language?
A constant in C programming is a value that cannot be modified during program execution. Constants are used to represent values that do not change, such as mathematical or physical constants, fixed values, or values that are known in advance.
A constant can hold only a single value in the C program. Also, constant values once assigned, can not be changed in the program.
There are several types of constants in C, including integer constants, floating-point constants, character constants, string constants, and enumerated constants.
Types of Constants in C
If you are wondering what are the types of constants in C language, then here is your answer.
There are two main types of constants: Primary and Secondary. These are further divided into several more types.
List of Primary Constants
1. Numeric Constants
-
Integer Constants
-
Real or floating-point Constants
2. Character Constants
-
Single Character Constants
-
String Constants
-
Backslash Character Constants
List of Secondary Constants
-
Array
-
Pointer
-
Structure
-
Union
-
Enum
Primary Constants in C Language
The primary constants in C programming are the basic constants that are directly represented in the code without any calculations.
There are two types of primary constants in C:
1. Numeric Constants in C
In C, a numeric constant is a value expressed in a form that represents a number. Numeric constants are used to represent integers, floating-point numbers, and other numerical values in a program.
Below, we have discussed the different types of numeric constants:
-
Integer Constants in C: These represent integer values and can be written in decimal, octal, or hexadecimal format.
Example:
int a = 123; // decimal
int b = 0123; // octal
int c = 0x7B; // hexadecimal
-
Floating-Point Constants (Real Constants): These represent real numbers with a fractional part. They can be written in decimal or exponential notation.
Example:
float x = 3.14;
double y = 1.23e-4;
2. Character Constants in C
A character constant in C language is a single character enclosed in single quotes. It is also known as a character literal.
Example:
char ch = 'A';
In this example, the character constant 'A' represents the character 'A' and is assigned to the variable ch.
Below, we are discussing the different types of character constants in C:
-
Single character constants: These represent a single character enclosed in single quotes.
Example:
char ch1 = 'A';
char ch2 = '\n'; // newline character
-
String Constants: String constants in C represent a sequence of characters enclosed in double-quotes.
Example:
char str1[] = "Hello, world!";
char str2[] = "This is a string constant.";
-
Backslash Character Constants: It is used to create special character constants, also known as escape sequences, representing characters that are difficult or impossible to type directly in the code.
Here are some common backslash character constants in C:
Example:
#include
int main() {
printf("Hello\tworld!\n");
printf("This is a backslash: \\ \n");
printf("This is a double quote: \" \n");
printf("This is a single quote: \' \n");
return 0;
}
Output:
Hello world!
This is a backslash: \
This is a double quote: "
This is a single quote: '
Secondary Constants in C
The secondary constants in C programming are derived or computed from primary constants.
There are several types of secondary constants in C, including:
1. Enumeration Constants in C
These are user-defined constants that are used to represent a set of related integer values. They are defined using the enum keyword.
Example:
enum color { RED, GREEN, BLUE };
2. Defined Constants
These are constants that are defined using the #define preprocessor directive. They are similar to primary constants, but they can be used to define more complex expressions.
Example:
#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))
3. Pointer Constants
These are constants that are used to represent memory addresses. They are derived from primary constants using the address-of operator &.
Example:
int a = 10;
int *ptr = &a;
4. Array Constants
Array constants are used to represent a fixed sequence of values. They are derived from primary constants using array initialization syntax.
Example:
int arr[] = { 1, 2, 3, 4 };
5. Macro Constants
These are similar to defined constants, but they are defined using the #define preprocessor directive with an empty argument list. They are typically used to define simple replacement text.
Example:
#define MESSAGE "Hello, world!"
Note that like primary constants, the values of secondary constants cannot be modified during program execution.
However, unlike primary constants, the type of a secondary constant is determined by its context in the program, rather than its format.
Examples of Constants in C Language
Here are some examples of constants in the C programming language:
1. Integer constants example
const int max = 100; // constant integer max with value 100
const int min = -50; // constant integer min with value -50
const int zero = 0; // constant integer zero with value 0
2. Floating point constants example
const float pi = 3.14159; // constant float pi with value 3.14159
const float e = 2.71828; // constant float e with value 2.71828
3. Character constants example
const char letter = 'A'; // constant character letter with value 'A'
const char newline = '\n'; // constant character newline with value newline
4. String constants examples
const char message[] = "Hello, world!"; // constant string message with value "Hello, world!"
const char name[] = "John Doe"; // constant string name with value "John Doe"
5. Enumeration constants example
enum colors {RED, GREEN, BLUE}; // enumeration constant colors with values RED, GREEN, and BLUE
enum days {MON, TUE, WED, THU, FRI, SAT, SUN}; // enumeration constant days with values MON, TUE, WED, THU, FRI, SAT, and SUN
6. Macro constants example
#define PI 3.14159 // macro constant PI with value 3.14159
#define MAX 100 // macro constant MAX with value 100
What is the Use of Constants in C Programming Language?
Constants in C are used to represent fixed values that do not change throughout the program. They are used to make the code more readable, easier to maintain, and less error-prone.
-
To declare fixed values
Constants are used to declare values that are known and fixed at compile time. Examples include mathematical constants like Pi or the speed of light and physical constants like the size of a buffer or the maximum number of items in a list.
-
To improve code readability
By using constants to represent fixed values, we make the code easier to understand and modify.
For instance, if we use the value 100 in multiple places in the code, it may not be clear what the number represents. If we use a named constant like MAX_SCORE instead, it is easier to understand the meaning of the value.
-
To ensure code correctness
Constants can help ensure the correctness of the program by eliminating hard-coded values, which can be prone to errors. For instance, if we use a constant to represent the size of a buffer, we can avoid buffer overflow errors caused by exceeding the buffer size.
-
To improve code maintainability
By using constants, we can make it easier to modify the program in the future. For example, if we need to change the maximum number of items in a list, we can simply change the value of the constant instead of modifying every instance of the number in the code.
How to Use Constants in C?
There are two ways to use constants in C language:
-
Using const keyword
-
Using #define preprocessor
Let’s understand both ways in detail with examples.
1. Using const keyword
Here's how you can define a constant in C using the const keyword:
Syntax
const data_type constant_name = value;
In the above syntax, data_type represents the data type of the constant, constant_name represents the name of the constant, and the value represents the value of the constant.
Example
Let's define a constant called PI of type double with the value of 3.14159:
const double PI = 3.14159;
Once you have defined the constant using the const keyword, you can use it in your program just like any other variable.
For example, you can use the PI constant to calculate the circumference of a circle:
#include <stdio.h>
const double PI = 3.14159;
int main() {
double radius = 5.0;
double area = PI * radius * radius;
printf("The area of a circle with radius %f is %f\n", radius, area);
return 0;
}
Here, we are using the PI constant to calculate the circumference of a circle with a radius of 5.0.
Note that once a constant is defined using the const keyword, its value cannot be changed during program execution. This helps prevent unintended changes to the value of a constant and makes your code more readable and maintainable.
2. Using #define preprocessor
Here's how you can define a constant in C using #define:
Syntax
#define constant_name value
In the above syntax, constant_name represents the name of the constant, and value represents the value of the constant.
Example
Let's define a constant called PI with the value of 3.14159 using #define:
#define PI 3.14159
Once you have defined the constant using #define, you can use it in your program just like any other variable.
For example, you can use the PI constant to calculate the circumference of a circle:
#include <stdio.h>
#define PI 3.14159
int main() {
double radius = 5.0;
double area = PI * radius * radius;
printf("The area of a circle with radius %f is %f\n", radius, area);
return 0;
}
In the above example, we are using the PI constant to calculate the circumference of a circle with a radius of 5.0.
Note: Unlike the const keyword, the #define directive does not define a variable that can be used to store the value of the constant. Instead, it simply replaces all occurrences of the constant name in your code with the constant value during compilation.
This means that you cannot take the address of a #define a constant or use it in an expression that requires an lvalue (i.e., a value that can appear on the left side of an assignment).
Rules of Constructing Constants in C
There are several rules that you should follow when constructing constants in C programming. Here are some of the key rules:
-
The format of the constant must be consistent with the data type. For example, integer constants should be represented using integer literals, floating-point constants should be represented using floating-point literals, and so on.
-
Integer constants can be represented in decimal, octal, or hexadecimal format. Decimal integers have no prefix, octal integers are prefixed with a "0", and hexadecimal integers are prefixed with "0x" or "0X".
-
Floating-point constants must include a decimal point or an exponent. They can be represented in decimal or exponential notation.
-
Character constants must be enclosed in single quotes. They can represent any printable character in the ASCII character set or certain escape sequences.
-
String constants must be enclosed in double-quotes. They can represent a sequence of characters, including escape sequences and Unicode characters.
-
Constants can be combined using operators to form more complex expressions. For example, you can add two integer constants to create a new integer constant.
-
Constants are case-sensitive in C, so "FOO" and "foo" are considered to be two different constants.
-
The value of a constant cannot be changed during program execution.
What is constant pointer in C?
A constant pointer in C language is a pointer that cannot be used to modify the memory it points to. It is declared using the const keyword before or after the * symbol in the pointer declaration.
For example, consider the following declaration:
int num = 10;
const int *ptr = #
Here, ptr is a constant pointer to an integer. This means that the memory location it points to cannot be modified using the ptr pointer. In other words, the value of num cannot be modified through ptr.
However, you can still modify the value of num directly, like this:
num = 20;
But if you try to modify the value of num through ptr, you will get a compiler error:
*ptr = 20; // error: assignment of read-only location '*ptr'
Constant pointers are useful in situations where you want to prevent accidental modification of data by the pointer.
For example, you might want to pass a pointer to a function that should not modify the data pointed to, or you might want to declare a global pointer that cannot be modified by other parts of the program.
Example of Constant Pointer in C Language
#include <stdio.h>
int main() {
int num = 10;
const int *ptr = #
printf("num = %d\n", num);
printf("*ptr = %d\n", *ptr);
// Attempt to modify the value using the constant pointer
*ptr = 20; // Compilation error: assignment of read-only location
// Attempt to modify the pointer itself
ptr = NULL; // This is allowed, as the pointer itself is not constant
return 0;
}
In this example, we declare an integer variable num with the value 10. We then declare a constant pointer ptr that points to num. The const keyword is used to make sure that the value pointed to by ptr cannot be modified.
We then print out the value of num and the value pointed to by ptr using the printf function. We can see that both values are the same since ptr points to num.
Next, we attempt to modify the value pointed to by ptr, by assigning the value 20 to *ptr. However, since ptr is a constant pointer, this results in a compilation error: "assignment of read-only location".
Finally, we attempt to modify the pointer itself by assigning NULL to ptr. This is allowed since the pointer itself is not constant.
Note that this example demonstrates the use of a pointer that points to a constant value. If you want to declare a pointer that is itself constant (i.e., cannot be made to point to a different memory location), you would use the second syntax I described earlier.
What are Symbolic Constants in C?
A symbolic constant in C is a name that represents a constant value in a program. Symbolic constants are also called "named constants" or "macros".
Symbolic constants are defined using the #define preprocessor directive. The #define directive is used to define a macro, which is a name that is replaced by its corresponding value in the code.
Example
#include
#define PI 3.14159
int main() {
double radius = 5.0;
double area = PI * radius * radius;
printf("The area of a circle with radius %.2f is %.2f\n", radius, area);
return 0;
}
In this example, we define the symbolic constant PI as 3.14159 using #define. We then declare a double variable radius with the value 5.0. We calculate the area of a circle with this radius using the formula PI * radius * radius and assign the result to a variable called an area.
Finally, we print out the radius and area of the circle using the printf function.
Note that when the code is compiled, the name PI is replaced with the corresponding value of 3.14159, so the calculation becomes 3.14159 * 5.0 * 5.0. This makes the code easier to read and understand since the value of PI is only defined once and is easily accessible from anywhere in the program.
Can Functions Return Enumeration Constants in C?
Yes, functions can return enumeration constants in C.
Enumeration constants, also known as "enums", are a set of named integer values.
Example
#include
enum Color {RED, BLUE, GREEN};
enum Color getFavoriteColor() {
return BLUE;
}
int main() {
enum Color favColor = getFavoriteColor();
printf("My favorite color is %d\n", favColor);
return 0;
}
In this example, we define an enumeration Color with three constants: RED, BLUE, and GREEN. We then define a function called getFavoriteColor() that returns a Color value, in this case, the BLUE constant.
In the main function, we call getFavoriteColor() and assign the result to a variable favColor. We then print out the value of favColor using printf. Since favColor is an enumeration constant, its value is an integer representing the position of the constant in the enum definition. In this case, BLUE is the second constant in the enum, so its value is 1.
So, to answer your question: Yes, functions can return enumeration constants in C, just like they can return any other data type.
Wrapping Up:
So, this was all about what are constants in C language with examples, types, rules, and more. You must practice things on your own using an online C compiler for better understanding.
For other concepts of this language, make sure to check our full C Programming Tutorial for Beginners, where we are covering everything in detail, including:
And more…