← Back to C Course | Chapter 1: Introduction & Basics | Lesson 20 of 21

C Constants

Const Keyword

Marking a variable const tells the compiler to reject any later attempt to reassign it, turning accidental modification of a value that should never change into a compile-time error instead of a silent runtime bug.

Example: Const Keyword

c
#include <stdio.h>
int main() {
	const int MAX = 100;
	printf("%d", MAX);
	return 0;
}

Define Directive

#define performs a simple text substitution before compilation even begins -- every occurrence of the defined name in your source is literally replaced with its value, so the compiler never even sees the original name.

Example: Define Directive

c
#include <stdio.h>
#define PI 3.14
int main() {
	printf("%.2f", PI);
	return 0;
}

Integer Constants

Integer constants can be written in decimal (42), octal with a leading 0 (052), or hexadecimal with a leading 0x (0x2A) -- all three represent the same value, and the choice is purely about which base is clearest for that context.

Example: Integer Constants

c
#include <stdio.h>
int main() {
	int decimalVal = 42;
	int octalVal = 052;
	int hexVal = 0x2A;
	printf("%d %d %d", decimalVal, octalVal, hexVal);
	return 0;
}

Real Constants

Real (floating-point) constants like 3.14 are stored as either float or double depending on context, and always include a decimal point or exponent so the compiler doesn't mistake them for integer literals.

Example: Real Constants

c
#include <stdio.h>
int main() {
	double pi = 3.14;
	printf("%.2f", pi);
	return 0;
}

Character Constants

A character constant like A is written in single quotes (not double, which is for strings) and is really just shorthand for that character's ASCII integer value -- A and 65 are interchangeable in C.

Example: Character Constants

c
#include <stdio.h>
int main() {
	char letter = 'A';
	printf("%c is %d", letter, letter);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.