C Literals

In C, literals are constant values used directly in your code to represent fixed data. They are used to assign specific values to variables, perform calculations, or compare values. C supports various types of literals to represent different types of data. Here are the most common types of literals in C:

1. Integer Literals: Integer literals represent whole numbers (integers) and can be positive or negative. They can be written in various formats:

  • Decimal (base 10): e.g., '42', '-123'
  • Octal (base 8): e.g., '052' (the leading 0 indicates octal)
  • Hexadecimal (base 16): e.g., '0x2A' or '0X2a'

Example:


int number = 42;
int negativeNumber = -123;
int octalNumber = 052;
int hexNumber = 0x2A;

2. Floating-Point Literals: Floating-point literals represent real numbers (numbers with a decimal point). They can be written in standard or exponential notation:

  • Standard notation: e.g., '3.14', '-0.001'
  • Exponential notation: e.g., '2.0e-3' (equals '0.002')
Example:

float pi = 3.14;
double smallValue = -0.001;
double scientificNotation = 2.0e-3;

3. Character Literals: Character literals represent single characters enclosed in single quotes ('). They can include regular characters, escape sequences, or special characters:

  • Regular character: e.g., 'A', '5'
  • Escape sequences: e.g., '\n' (newline), '\t' (tab), '\'' (single quote)
  • Special characters: e.g., '\0' (null character), '\a' (alert or bell)
Example:

char letter = 'A';
char newline = '\n';
char nullChar = '\0';

4. String Literals: String literals represent sequences of characters enclosed in double quotes ("). Strings are null-terminated, which means they end with a null character '\0'.

Example:


char greeting[] = "Hello, world!";

5. Boolean Literals: C does not have native boolean literals like some other languages (e.g., 'true' or 'false'). Instead, integers are often used to represent boolean values, where '0' typically represents 'false', and any non-zero value represents 'true'.

Example:


int isTrue = 1; // Represents true
int isFalse = 0; // Represents false

6. Constants: Constants are predefined values, often used for symbolic representation of fixed values. They are typically defined using the #define preprocessor directive or using const keyword.

Example:


#define PI 3.14159265359

or


const int x = 10; // Declares a constant integer

These are some of the common types of literals in C. They are essential for initializing variables, performing calculations, and representing fixed data in your C programs.