C Constants

1. What is a Constant?

  • A constant is a fixed value that cannot be altered by the program once defined.

  • Useful for values like pi, tax rates, maximum limits, or configuration values.


2. Types of Constants in C

Type Description Example
Literal Constant Directly written in code 100, 3.14, 'A'
Symbolic Constant Defined using #define or const keyword #define PI 3.14 or const int MAX = 100;

3. Literal Constants

  • Integer constant: 10, -25

  • Floating-point constant: 3.14, -0.5

  • Character constant: 'A', '9'

  • String constant: "Hello"

Example:

#include <stdio.h>

int main() {
printf("Integer: %d\n", 10);
printf("Float: %.2f\n", 3.14);
printf("Char: %c\n", 'A');
printf("String: %s\n", "Hello World");
return 0;
}

Output:

Integer: 10
Float: 3.14
Char: A
String: Hello World

4. Symbolic Constants using #define

  • Use #define to give a name to a constant.

  • Advantage: easier to update value in one place.

#include <stdio.h>
#define PI 3.14159
#define MAX 100

int main() {
printf("PI: %.2f\n", PI);
printf("MAX: %d\n", MAX);
return 0;
}

Output:

PI: 3.14
MAX: 100

#define does not allocate memory; it’s a preprocessor directive.


5. Symbolic Constants using const Keyword

  • const defines a typed constant.

  • Memory is allocated, and value cannot be changed.

#include <stdio.h>

int main() {
const int MAX = 100;
const float PI = 3.14159;

printf("MAX: %d\n", MAX);
printf("PI: %.2f\n", PI);

// MAX = 200; // Error: cannot modify const variable

return 0;
}

Output:

MAX: 100
PI: 3.14

6. Key Points About Constants

  1. Constants cannot be modified once defined.

  2. #define is handled by the preprocessor; const is a typed variable.

  3. Constants improve code readability and maintainability.

  4. Use const when you want type checking; use #define for preprocessor constants.


7. Combined Example

#include <stdio.h>
#define TAX_RATE 0.18
const int MAX_USERS = 50;

int main() {
float price = 1000;
float tax = price * TAX_RATE;

printf("Price: %.2f\n", price);
printf("Tax: %.2f\n", tax);
printf("Maximum Users: %d\n", MAX_USERS);

return 0;
}

Output:

Price: 1000.00
Tax: 180.00
Maximum Users: 50

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *