Syntax
It has the following syntax:
const data_type var_name = value;
In this syntax,
- const: It represents the const variable.
- data_type: It represent the type of data.
- var_name: It represents the name of the variable.
Simple Constant Example in C
Let's consider an example to demonstrate the concept of Constants in the C programming language.
Example
#include <stdio.h>
int main() { //Main Function
const int MAX = 150; // constant declaration
printf("The value of MAX is: %d\n", MAX);
return 0;
}
Output:
The value of MAX is: 150
Explanation:
In this instance, we have defined a constant integer MAX utilizing the const keyword with an assigned value of 150. Subsequently, it displays this value, guaranteeing its immutability throughout the program's execution.
Ways to define constant in C
There are primarily two methods of declaring constants in C programming:
- using the const keyword
- utilizing the #define preprocessor
Here, we will explore these various methods individually.
1) Using const keyword
In C programming, the const keyword is primarily used to declare a constant value within a program. By utilizing the const keyword, we ensure that the value of the constant remains unchangeable throughout the program's execution.
Syntax
It has the following syntax:
const data_type var_name = value;
const float PI=3.14;
Now, the value of PI variable can't be changed.
Constant Example using const Keyword in C
Let's consider an example to demonstrate the concept of constants in C programming by utilizing the const keyword.
Example
#include<stdio.h>
int main(){ //main function
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
The value of PI is: 3.140000
Explanation:
In this instance, we are utilizing the constant float PI which is defined with the const keyword. Subsequently, the value of PI is displayed using the printf function.
If we attempt to modify the value of PI, it will result in a compilation error.
Example
#include<stdio.h>
int main(){ //main function
const float PI=3.14;
PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object
2) Using #define preprocessor
In C programming, we have the option to utilize the #define preprocessor directive for declaring constants without the need to specify a specific data type. This directive aids in substituting all occurrences of the constant with its assigned value during the compilation process. It is frequently employed for establishing unchanging values like mathematical constants, configuration settings, and flags. This approach significantly contributes to enhancing the clarity and manageability of our code.
Syntax
It has the following syntax:
#define constant_name value
Constant Example using #define directives in C
Let's consider an example to demonstrate the usage of constants in C programming using the #define directives.
Example
#include <stdio.h>
#define PI 3.14159 // Defining constant using #define
int main() { //main function
float rad = 6.0; //radius
float area = PI * rad * rad;
printf("Area of the circle: %.2f\n", area);
return 0;
}
Output:
Area of the circle: 113.10
Explanation:
In this instance, we've utilized #define directives to establish a constant PI with the precise value of 3.14159. Subsequently, we compute the circle's area by applying the formula with a radius of 6.0. Ultimately, the result is displayed through the printf function.
Types of Constant in C
There are different types of Constants in C. Some of them are as follows:
- Integer Constants
- Floating-Point Constants
- Character Constants
- String Constants
- Enumeration Constants
- Double Precision Floating-Point Constant
Here, we will explore each of these constants individually,
1) Integer Constants
In the realm of C programming, integer constants stand for complete numbers devoid of fractions or decimals. These constants carry the ability to be either positive or negative and can be expressed without quotation marks. They are formable in various bases such as decimal (base 10), octal (base 8), and hexadecimal (base 16).
Example:
int daysInWeek = 7; // Integer constant 7
int months = 12; // Integer constant 12
Rules for Integer Constants in C
Several rules for integers constants in C are as follows:
- The digits of an integer constantcan range from 0 to 9.
- A decimal pointshould not be present in an integer constant.
- Positiveor negative integer constants are also possible.
- We can add a suffixto a constant's name to define its type. 'U' or 'u' stands for unsigned, 'L' or 'l' for long, or 'LL' or 'll' for long long.
Integer Constants possess various fundamental values. In this section, we will delve into each of these fundamental values individually.
Decimal Constants
In the C programming language, a decimal constant signifies a complete number in the base 10 system. It consists of digits ranging from 0 to 9. Defining a decimal constant follows a straightforward syntax where you simply write the desired value.
Decimal Constants example in C
Let's consider an example to demonstrate the integer constant by utilizing the decimal constant in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int decimal = 42;
printf("The decimal constant is: %d\n", decimal);
return 0;
}
Output:
The decimal constant is: 42
Octal Constant
In the C programming language, the base 8 value is denoted by an octal constant. It is indicated by a '0' (zero) at the beginning to signify its octal nature and consists of digits from 0 to 7.
Octal Constant Example in C
Let's consider a scenario to demonstrate the octal constant in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int octal = 052; // Octal representation of decimal 42
printf("The octal constant is: %o\n", octal);
return 0;
}
Output:
The octal constant is: 52
Rules for Octal Constants
Several rules for octal constants in C are as follows:
- Base 8is used for writing octal constants.
- They are made up of the numerals 0through 7.
- A '0' (zero)should come before any octal constants.
Hexadecimal Constant
In the C programming language, the hexadecimal constant denotes a value in base-16. It incorporates the characters A to F (or a to f) along with the numbers 0 to 9 to symbolize values ranging from 10 to 15. To distinguish it as a hexadecimal constant, it is prefixed with '0x' or '0X'.
Hexadecimal constants Example in C
Let's consider an example to demonstrate the integer constant utilizing the hexadecimal constant in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int hexadecimal = 0x2A; // Hexadecimal representation of decimal 42
printf("The hexadecimal constant is: %x\n", hexadecimal);
return 0;
}
Output:
The hexadecimal constant is: 2a
Rules for Hexadecimal Constants in C
Several rules for Hexadecimal Constants in C are as follows:
- Constants in hexadecimal are expressed in base 16.
- In order to represent numbers from 10to 15, they are made up of numerals 0 to 9 and letters A to F (or a to f).
- Prefixing a hexadecimal constantwith '0x' or '0X' is appropriate.
2) Real or Floating-Point Constant
In the realm of C programming, a real or floating-point constant denotes the fractional part or the exponent of a numerical value. This type of constant can be articulated using a decimal point, the letter "E", or the symbol "e" in either exponential or decimal form.
Real or Floating-Point Constant Example in C
Let's consider an example to demonstrate the floating-point constant in the C programming language.
Example
#include <stdio.h>
int main() { //main function
float real = 3.14;
printf("The real or floating-point constant is: %f\n", real);
return 0;
}
Output:
The real constant is: 3.140000
Rules for Floating-Point Constants in C
Several rules for floating-point constants in C are as follows:
- A decimal point, an exponent, or digits can all be found in floating-point constants.
- Either exponential notationor decimal notation can be used to write them.
- 'E'or 'e' can be used to denote an exponent.
- We can add a suffix to a constant's nameto define its type. For instance, "F" or "f" stands for float and "L" or "l" for long double.
3) Character Constant
In the C language, a character constant denotes a solitary character enclosed within single quotation marks.
Character Constant Example in C
Let's consider a scenario to demonstrate the character constant in the C programming language.
Example
#include <stdio.h>
int main() { //main function
char character = 'A';
printf("The character constant is: %c\n", character);
return 0;
}
Output:
The character constant is: A
Rules for Character Constants in C
Several regulations for character literals in C include the following:
- Character constants depict individual characters enclosed in single quotation marks.
- These characters can be a single letter or an escape sequence like "n" to represent a newline or "t" for a tab.
4) String Constant
In the C programming language, a sequence of characters enclosed in double quotation marks is denoted by a string literal. It constitutes a character array terminated by the null character \0.
String Constant Example in C
Let's consider an example to demonstrate the concept of a string constant in the C programming language.
Example
#include <stdio.h>
int main() { //main function
char string[] = "Hello, World!";
printf("The string constant is: %s\n", string);
return 0;
}
Output:
The string constant is: Hello, World!
Rules for String Constants in C
Several guidelines for string literals in C include:
- A string constant is a sequence of characters enclosed in double quotation marks, defining string literals.
- String constants are essentially arrays of characters terminated with the null character "\0".
5) Enumeration Constants
In the realm of C programming, enumeration constants serve as custom-defined constants that signify a collection of integer values. By employing the enum keyword, we can establish these enumeration constants, allowing for the creation of a series of named integer constants. This practice significantly enhances the clarity and structure of code.
Enumeration Constant Example in C
Let's consider a scenario to demonstrate the usage of enumeration constants in the C programming language.
Example
#include <stdio.h>
enum Week_Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
int main() { //main function
enum Week_Day today = TUESDAY;
printf("The value of today is: %d\n", today);
return 0;
}
Output:
The value of today is: 2
6) Double Precision Floating-Point Constant
In the realm of C programming, the double-precision floating-point constant resembles a floating-point constant but delivers a greater level of precision compared to the float type. These constants are stored utilizing the double data type, which consumes a larger amount of memory (8 bytes) and grants a precision of over 15-17 digits.
A sample of a double precision floating-point constant in the C programming language: ```
const datatype varname = value;
Let's consider an example to demonstrate a double-precision floating-point constant in the C programming language.
### Example
include <stdio.h>
int main { ///main function
double pi = 3.141592653589793; //using double floating-point constant
printf("The value of pi is: %.15lf\n", pi);
return 0;
}
Output:
The value of pi is: 3.141592653589793
## Advantages of C Constants:
Several main advantages of constants in C programming language are as follows:
- Programmers may use constants to provide names that have meaning to fixed numbers, which makes the code simpler to comprehend and update.
- Constants assist in avoiding the usage of magic numbers, which are hard-coded values, in the code. Instead, constants offer named representations of such values, enhancing the code's readability.
- Constants are reusable throughout the program, which allows for constant values in various locations and lowers the possibility of errors brought on by typos or inconsistent values.
- Calculations or processes inside the program can be optimized by using certain constants, such as mathematical or physical constants.
- A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming", etc.
## Conclusion
In summary, constants are immutable values that remain unchanged throughout program execution, promoting stability, clarity, and safety within our codebase. Constants can be declared using the const keyword, #define preprocessor directive, or enum for defining named sets of integers. The C programming language accommodates various constant types including integers, floating-point numbers, characters, strings, and enumerations. Leveraging constants effectively improves code readability, safeguards against inadvertent alterations, and simplifies maintenance while reducing the likelihood of errors.