In this tutorial we will learn about Constants in C, different types of constants, declaration of constants and #define preprocessor directives in C programming.
Constants in C refer to fixed values that program cannot change during the time of execution. Constants are also known as literals.
A constant can be of any data type like character constant, integer constant, string constant etc.
For Example :
'A', 1234, 123.5, "TechCrashCourse"
Constants in C are like normal variables, the only difference is, their values cannot be changed by the program once they are defined.
Character Constants
Characters constants are enclosed between a pair or single quote. We can store a character constant in a variable of char data type. The ASCII value of character constants are stored internally. “%c” format specifier is used to print character constants.
For Example:
'a', 'A', '1', '#' are character constants
#include<stdio.h> int main() { char c = 'E'; printf("Character Constant : %c", c); return(0); }
Output
Character Constant : E
Backslash Character Constants
There are some characters which are impossible to enter into a string from keyboard like backspace, vertical tab etc. Because of this reason, C includes a set of backslash character which have special meaning in C language.
The backslash character ('\') changes the interpretation of the characters by compiler.
For Example:
If we include '\n'(newline character) in a string like "TechCrash\nCourse" then compiler will print the characters after \n in next line.
Escape Sequence | Description |
---|---|
\” | Double quote(") |
\' | Single quote(') |
\\ | Backslash Character(\) |
\b | Backspace |
\f | Form feed |
\n | New line |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\a | Alert or bell |
\? | Question mark |
\0 | Null character |
#include<stdio.h> int main() { printf("Tech\nCrash\nCourse"); return(0); }Output
Tech Crash Course
Integer Constants
Integer constants are whole numbers without any fractional part or exponential part. It can either be positive or negative, If no sign precedes it is assumed to be positive by default.
The range of integer constant depends on operating system. In a 16-bit system range of integer literal is -32768 to 32767.
For Example:
3, -3, 67L, 0x2A are Integer Constants
Prefix | Description | Base | Example |
---|---|---|---|
0x or 0X | Hexadecimal Number | 16 | 0x5C, 0x22 |
0 | Octal Number | 8 | 012C, 0243 |
Nothing | Decimal Number | 10 | 25, 100 |
- F : Floating-point number
- L : Long
- U : Unsigned
- Unsigned Integer Constant : 100U, 565U
- Long Constant : 67L, -2398876L
- Unsigned Long Constant : 55UL, 77652UL
- Decimal Constants : 85, -54
- Octal Constants : 0213, 045
- Hexadecimal Constants : 0x4b, 0x2A
Floating Point Constants
A floating point constant has a integer part, a decimal point, a fractional part and may contain an exponential part. Floating point literal may be positive or negative but must have a decimal point. You can also represent floating point literals in scientific notation.
For Example: 1234.5432, -100.001, 2.37E-3
String Constants
A string constant is a set of characters enclosed between a pair of double quotes. A string literal is actually stored as a character array. A string literal may contain any number of characters including alphanumeric characters, escape characters, graphical characters etc.
For Example- "" : Null String.
- "A" : String literal having single characters.
- "ABc12.iyu" : String literal with multiple characters.
- "ABd jjuh\n" : String with spaces and escape characters.
#include <stdio.h> int main(){ printf("Printing Integer Constants\n"); printf("%d %u \n\n", 543, 7653U); printf("Printing Long Constants\n"); printf("%ld\n\n", 554365L); printf("Printing Radical Constants\n"); printf ("%d %x %o\n\n", 2015, 0x7df, 02015); return 0; }Output
Printing Integer Constants 543 7653 Printing Long Constants 554365 Printing Radical Constants 2015 7df 2015
Declaration of Constants in C
We can define constants in C in two ways.- Using const keyword in variable declaration.
- Using #define preprocessor directives.
const float PI = 3.141;
Above statement declares a constant PI with initial value 3.141. After declaration, any code cannot modify value of PI.
C program to show the use of const keyword to define a constant
#include<stdio.h> int main() { float radius; const float PI = 3.141; printf("Enter Radius of Circle\n"); scanf("%f", &radius); printf("Area of Circle : %f", PI*radius*radius); return(0); }
Output
Enter Radius of Circle 3.0 Circumference of Circle : 18.846000
#include Preprocessor Directive for defining C Constant
We can use #define preprocessor directive to define a constant as per following syntax.
#define PI 3.141 C program to shows the use of #define Preprocessor Directive to define a constant
#include<stdio.h> #define PI 3.141 int main() { float radius; printf("Enter Radius of Circle\n"); scanf("%f", &radius); printf("Circumference of Circle : %f", 2*PI*radius); return(0); }Output
Enter Radius of Circle 3.0 Circumference of Circle : 18.846000
Benefits of Constants and Literals
- Readability and Maintainability : In C programming, constants and literals have many benefits: Readability, Maintainability: Code is easier to read with named constants and literals. Descriptive names explain values' purposes, minimizing remarks.
- Code Consistency : Consistent usage of constants and literals follows a coding standard, making code more consistent and manageable.
- Ease of Modification : Constants simplify program-wide value changes. Modifying a constant at its declaration point changes all references instead than looking for each literal.
- Error Prevention : Constants can avoid unintentional crucial value changes. Declaring a value constant prevents program execution from changing it.
Best Practices for Using Constants and Literals
- Use Enums for Named Constants : Enumeration constants should be taken into consideration while working with a collection of linked constant values. Enums give numeric values meaningful names.
enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; enum Days today = Wednesday;
- Avoid Global Constants When Possible : Avoid Using Global Constants Whenever Possible: Although they could be required in some circumstances, try to stay away from using global constants excessively. Modularity is enhanced by keeping constants inside a confined scope.
- Prefer const over #define : Choose const over #define: Whenever feasible, declare constants using the const keyword rather than the preprocessor instruction #define. Const is scoped and offers type safety.
// Avoid: #define MAX_SIZE 100 // Prefer: const int MAX_SIZE = 100;
- Group Related Constants : Use an enumeration or a structure to group related constants that are present in your program in numerous instances. This increases maintainability and organizes the code better.
// Grouping related constants using a structure struct Constants { const int MAX_SIZE; const float PI; }; const struct Constants constants = {100, 3.14};
- Use enum for Named Integer Constants : When defining named integer constants, prefer using an enumeration. This makes the code more readable and avoids potential issues with #define.
// Avoid: #define WEEKDAYS 7 // Prefer: enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
Conclusion
Writing concise, manageable, and error-resistant C code requires understanding constants and literals. This tutorial covered integer, floating-point, character, and string C constants and literals. We covered constants and literals' advantages and recommended practices for utilizing them in code.