C Constants, Literals, and Best Practices
Master constants, literals, tokens, variable declaration rules, and professional coding practices for writing clean, maintainable C code.
Constants & Literals
Fixed values in C programs
Tokens & Rules
C language building blocks
Best Practices
Write professional code
Constants in C
Constants are fixed values that cannot be changed during program execution. C supports several types of constants, each with specific characteristics and uses.
Types of Constants
- Integer Constants: Whole numbers (e.g., 100, -50, 0xFF)
- Floating Constants: Decimal numbers (e.g., 3.14, -2.5e3)
- Character Constants: Single characters (e.g., 'A', '5', '\n')
- String Constants: Text sequences (e.g., "Hello, World!")
- Symbolic Constants: Defined using #define or const
Defining Constants
C provides two ways to define constants:
- Using
#definepreprocessor directive - Using
constkeyword
#include <stdio.h>
// Preprocessor constants (no memory allocation)
#define PI 3.1415926535
#define MAX_USERS 100
#define COMPANY_NAME "Nikhil LearnHub"
#define NEWLINE '\n'
// Constant variables (allocates memory)
const int DAYS_IN_WEEK = 7;
const float GRAVITY = 9.81;
const char TAB = '\t';
int main() {
// Integer constants
int decimal = 100;
int octal = 0144; // Octal: starts with 0
int hexadecimal = 0x64; // Hexadecimal: starts with 0x
// Floating point constants
float regular = 3.14;
float scientific = 3.14e2; // 3.14 × 10² = 314.0
// Character constants
char letter = 'A';
char escape = '\n'; // Newline character
// String constants
char greeting[] = "Hello, C Programmers!";
printf("PI: %.10f%c", PI, NEWLINE);
printf("Max Users: %d%c", MAX_USERS, NEWLINE);
printf("Days in Week: %d%c", DAYS_IN_WEEK, NEWLINE);
printf("Gravity: %.2f m/s²%c", GRAVITY, NEWLINE);
printf("Company: %s%c", COMPANY_NAME, NEWLINE);
return 0;
}
#define constants and camelCase or snake_case for const variables. Always add comments explaining the purpose of important constants.
Literals in C
Literals are constant values that are directly used in the source code. They represent fixed values that don't change.
| Literal Type | Description | Examples | Suffixes |
|---|---|---|---|
| Integer Literals | Whole numbers without decimal point | 42, -15, 075 (octal), 0x2A (hex) |
U (unsigned), L (long), LL (long long) |
| Floating Literals | Numbers with decimal point or exponent | 3.14, -0.001, 2.5e-3, 1.0E+5 |
F (float), L (long double) |
| Character Literals | Single character enclosed in single quotes | 'A', '5', '\n', '\t' |
Escape sequences: \n, \t, \\, etc. |
| String Literals | Sequence of characters in double quotes | "Hello", "C\tProgramming\n" |
Automatically null-terminated (\0) |
#include <stdio.h>
int main() {
// Integer literals with different bases
int decimal = 100; // Decimal (base 10)
int octal = 0144; // Octal (base 8) - starts with 0
int hexadecimal = 0x64; // Hexadecimal (base 16) - starts with 0x
// Integer literals with suffixes
unsigned int age = 25U; // Unsigned
long population = 7800000000L; // Long
long long bigNumber = 9223372036854775807LL; // Long long
// Floating point literals
float pi = 3.14159F; // Float suffix
double e = 2.71828; // Double (default)
long double ld = 1.23456789L; // Long double
// Scientific notation
float avogadro = 6.022e23F; // 6.022 × 10²³
// Character literals with escape sequences
char newline = '\n';
char tab = '\t';
char backslash = '\\';
char singleQuote = '\'';
char nullChar = '\0';
char bell = '\a'; // Alert (bell) sound
// String literals
char message[] = "Hello,\tWorld!\n";
char path[] = "C:\\Programs\\C\\";
printf("Decimal: %d\n", decimal);
printf("Hexadecimal: 0x%x\n", hexadecimal);
printf("Pi: %.5f\n", pi);
printf("Avogadro's Number: %e\n", avogadro);
printf("Message: %s", message);
printf("Bell sound: %c", bell);
return 0;
}
C Tokens
Tokens are the smallest individual elements in a C program. The C compiler breaks down source code into tokens during compilation.
| Token Type | Description | Examples |
|---|---|---|
| Keywords | Reserved words with special meaning | int, if, else, while, return |
| Identifiers | Names given to program elements | main, printf, counter, calculateSum |
| Constants | Fixed values | 100, 3.14, 'A', "Hello" |
| String Literals | Text enclosed in double quotes | "Hello, World!", "C Programming\n" |
| Operators | Symbols that perform operations | +, -, *, /, =, == |
| Separators | Punctuation marks | ;, ,, {, }, (, ) |
Token Example
For the statement:
int sum = a + 10;
Tokens are:
int(keyword)sum(identifier)=(operator)a(identifier)+(operator)10(constant);(separator)
Variable Declaration Rules
Variables in C must follow specific rules for declaration and naming. Understanding these rules is crucial for writing valid C code.
Valid Variable Names
- Must begin with a letter or underscore
- Can contain letters, digits, and underscores
- Case-sensitive (
age≠Age≠AGE) - Cannot be a C keyword
- No spaces or special characters (except _)
Examples:
counter_tempuserNameMAX_SIZEstudent2
Invalid Variable Names
2ndPlace(starts with digit)user-name(contains hyphen)user name(contains space)int(C keyword)price$(contains special character)return(C keyword)
#include <stdio.h>
// Global variables (declared outside functions)
int globalCounter = 0;
const double TAX_RATE = 0.18;
int main() {
// Valid variable declarations
int age = 25;
float _temperature = 36.6;
char firstInitial = 'J';
double accountBalance = 1250.75;
// Multiple declarations of same type
int x, y, z;
float width = 10.5, height = 20.3, depth;
// Declaration with initialization
int counter = 0;
char newline = '\n';
// Using the variables
x = 10;
y = 20;
z = x + y;
depth = width * height;
printf("Age: %d\n", age);
printf("Temperature: %.1f\n", _temperature);
printf("Initial: %c\n", firstInitial);
printf("Sum: %d\n", z);
printf("Volume: %.2f\n", depth);
printf("Tax Rate: %.2f\n", TAX_RATE);
// Redeclaration is NOT allowed
// int age = 30; // ERROR: redeclaration of 'age'
// Reassignment is allowed
age = 30; // OK: changing value
printf("New Age: %d\n", age);
return 0;
}
Naming Conventions & Readability
Good naming conventions improve code readability, maintainability, and collaboration. Follow these industry-standard practices.
Naming Styles
| Style | Example | Used For |
|---|---|---|
| camelCase | calculateTotal |
Variables, functions |
| PascalCase | CalculateTotal |
Types, classes (in C++) |
| snake_case | calculate_total |
Variables, functions |
| UPPER_SNAKE_CASE | MAX_SIZE |
Constants, macros |
| kebab-case | calculate-total |
Not used in C (invalid) |
Best Practices
- Use descriptive, meaningful names
- Avoid abbreviations unless widely known
- Be consistent throughout the codebase
- Use nouns for variables, verbs for functions
- Avoid single-letter names except for counters
- Don't use names too similar to each other
Good Examples
studentCountinstead ofccalculateAverageinstead ofavgisDataValidinstead ofdvMAX_BUFFER_SIZEinstead ofmbsfileNameinstead offn
Poor Examples
a,b,c(too vague)temp(what kind of temp?)data1,data2(not descriptive)compute(compute what?)flag(what does it flag?)
#include <stdio.h>
#include <stdbool.h>
// Constants (UPPER_SNAKE_CASE)
#define MAX_STUDENTS 100
#define PI 3.1415926535
// Global variables (descriptive names)
int studentCount = 0;
float classAverage = 0.0;
// Function prototypes (camelCase for functions)
float calculateAverage(int scores[], int count);
bool isValidScore(int score);
void printStudentReport(int id, char name[], float grade);
int main() {
// Local variables (camelCase or snake_case)
int testScores[MAX_STUDENTS];
int currentScore;
bool isProcessingComplete = false;
char studentName[50];
// Loop counter (short names acceptable)
for (int i = 0; i < 10; i++) {
testScores[i] = i * 10;
}
// Boolean variables (prefix with 'is', 'has', 'can')
bool hasPassedExam = true;
bool isEligibleForScholarship = false;
// Pointer variables (prefix with 'p' optionally)
int *pScore = &testScores[0];
char *pName = studentName;
// Arrays (plural names)
float temperatures[7];
char fileNames[20][100];
printf("Maximum students: %d\n", MAX_STUDENTS);
printf("PI value: %.10f\n", PI);
return 0;
}
float calculateAverage(int scores[], int count) {
int total = 0;
for (int i = 0; i < count; i++) {
total += scores[i];
}
return (float)total / count;
}
bool isValidScore(int score) {
return (score >= 0 && score <= 100);
}
Comments and Documentation
Comments are essential for explaining code logic, documenting functions, and improving maintainability. C supports both single-line and multi-line comments.
Comment Types
// Single-line |
C99 standard onward |
/* Multi-line */ |
Traditional C comments |
Best Practices:
- Explain WHY, not WHAT (code should be self-explanatory)
- Keep comments up-to-date with code changes
- Avoid redundant or obvious comments
- Use comments for complex algorithms
Documentation Guidelines
- Document function purpose, parameters, and return value
- Explain assumptions and constraints
- Note side effects if any
- Include examples for complex functions
- Document file purpose at the top
/*
* File: calculator.c
* Author: Nikhil LearnHub
* Description: Basic arithmetic operations with input validation
* Created: 2024
* Version: 1.0
*/
#include <stdio.h>
#include <stdbool.h>
// Constants
#define MAX_OPERAND 1000.0
#define MIN_OPERAND -1000.0
/**
* @brief Validates if a number is within acceptable range
* @param number The number to validate
* @return true if number is within range, false otherwise
*/
bool isValidOperand(double number) {
return (number >= MIN_OPERAND && number <= MAX_OPERAND);
}
/**
* @brief Calculates the sum of two numbers
* @param a First operand
* @param b Second operand
* @return Sum of a and b
* @note Returns 0.0 if operands are invalid
*/
double add(double a, double b) {
// Validate inputs before processing
if (!isValidOperand(a) || !isValidOperand(b)) {
printf("Error: Operand out of range\n");
return 0.0;
}
return a + b;
}
/**
* @brief Calculates the quotient of two numbers
* @param dividend The number to be divided
* @param divisor The number to divide by
* @return Quotient of dividend ÷ divisor
* @note Returns 0.0 if divisor is zero or operands are invalid
*/
double divide(double dividend, double divisor) {
// Check for division by zero
if (divisor == 0.0) {
printf("Error: Division by zero\n");
return 0.0;
}
// Validate operands
if (!isValidOperand(dividend) || !isValidOperand(divisor)) {
printf("Error: Operand out of range\n");
return 0.0;
}
return dividend / divisor;
}
int main() {
double num1, num2, result;
// Get user input
printf("Enter first number: ");
scanf("%lf", &num1);
printf("Enter second number: ");
scanf("%lf", &num2);
// Perform addition
result = add(num1, num2);
printf("Sum: %.2f\n", result);
// Perform division
result = divide(num1, num2);
printf("Quotient: %.2f\n", result);
return 0;
}
Key Takeaways
- Constants are fixed values defined with
#defineorconstkeyword - Literals are constant values directly written in code (numbers, characters, strings)
- Tokens are the basic building blocks of C programs (keywords, identifiers, operators, etc.)
- Variable names must follow specific rules and should be descriptive
- Use consistent naming conventions (camelCase, snake_case, UPPER_CASE) for different elements
- Comments should explain WHY code exists, not WHAT it does
- Good code is self-documenting with meaningful names and clear structure