📘

Constants in C Language

Jul 11, 2024

Constants in C Language

Introduction

  • Understanding constants is essential before writing a C program.
  • Constants have fixed values that do not change during the execution of a program.
  • Types of constants:
    • Symbolic constants
    • Numeric constants
    • Character constants

Symbolic Constants

  • Defined using #define directive.
  • Example: #define PI 3.14
  • The value defined cannot be changed.
  • Use uppercase for symbolic constant names for better distinction.

Types of Constants

  1. **Numeric Constants:
    • Integer Constants:
      • Decimal Constants (Base 10): Valid values from 0-9 (e.g., 10, 5).
      • Octal Constants (Base 8): Starts with 0 (e.g., 05).
      • Hexadecimal Constants (Base 16): Starts with 0x or 0X, uses 0-9 and A-F letters (e.g., 0xA5).
    • Real Constants (Floating Point Constants):
      • With Decimal Point (e.g., 12.56).
      • Exponential Form: Mantissa e Exponent (e.g., 1.23e4).
  2. **Character Constants:
    • Single Character Constants: Enclosed within single quotes (e.g., 'A').
    • Backslash Character Constants (Escape Sequences): E.g., \n for newline.
  3. **String Constants:
    • Sequence of characters enclosed within double quotes (e.g., "hello").
    • Always ends with a null character (\0).**

Rules for Declaring Integer Constants

  • No commas or spaces between digits.
  • Decimal integers cannot have leading zeros (unless it's meant to be octal).
  • The sign can be either + or - (default is +).

Rules for Declaring Real Constants

  • Must have a decimal point.
  • Can be signed (+ or -, default is +).
  • Only one decimal point allowed.
  • Can be expressed in exponential form.

Rules for Declaring Character Constants

  • Enclosed in single quotes.
  • Can include any single character, digits, or special characters.
  • Represented internally as ASCII values.
  • Constants like \n, \t, etc., have special meanings.

Rules for Declaring String Constants

  • Enclosed in double quotes.
  • Can include letters, digits, spaces, and special characters.
  • Always ends with a null character (\0).

Declaring Constants in C

  • Using const keyword:
    • Example: const int a = 10;
    • Makes a value immutable within the program.
  • Using #define directive:
    • Example: #define A 10
    • No equal sign or semicolon used.

Summary

  • Constants in C are important for maintaining fixed values throughout the program.
  • Proper declaration ensures correct usage and prevents unintended changes.
  • Having a clear understanding of types and rules for constants makes programming in C more efficient.