In C, constants and literals are fundamental concepts used to represent fixed values in a program.
Constants
Constants are values that do not change during the execution of a program. They can be of various types, including integer, floating-point, character, and more. In C, constants can be defined using the const
keyword or using the #define
preprocessor directive.
1. Using const
Keyword
You can declare a constant variable using the const
keyword. Once a variable is declared as const
, its value cannot be modified.
const int maxSize = 100; const float pi = 3.14159; const char newline = '\n';
2. Using #define
Preprocessor Directive
You can also define constants using the #define
directive. This method does not create a variable but replaces the constant’s name with its value during preprocessing.
#define MAX_SIZE 100 #define PI 3.14159 #define NEWLINE '\n'
Literals
Literals are the actual values assigned to constants or variables. They represent fixed values written directly in the code. C supports several types of literals:
1. Integer Literals
Integer literals represent whole numbers without any fractional part.
int a = 10; // Decimal literal int b = 0xFF; // Hexadecimal literal (prefix 0x or 0X) int c = 077; // Octal literal (prefix 0)
2. Floating-Point Literals
Floating-point literals represent numbers with a fractional part.
float x = 3.14; double y = 0.12345;
3. Character Literals
Character literals represent single characters enclosed in single quotes.
char ch1 = 'A'; char ch2 = '\n'; // Newline character
4. String Literals
String literals represent a sequence of characters enclosed in double quotes.
char str[] = "Hello, World!";
5. Boolean Literals
In C, there’s no built-in boolean type like in C++, but you can use 0
and 1
to represent false
and true
, respectively.
int isTrue = 1; // True int isFalse = 0; // False
Example Program
Here’s an example that demonstrates the use of constants and literals in C:
#include <stdio.h> #define PI 3.14159 // Define a constant using #define int main() { const int radius = 5; // Define a constant using const float area; // Using literals and constants area = PI * radius * radius; printf("Area of the circle: %.2f\n", area); return 0; }
In this program, PI
is defined using #define
, and radius
is defined using const
. The literal 5
is used as the value for radius
, and the literal 2
is used in the printf
format specifier.