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
#include <stdio.h>
int main() {
const int MAX = 100;
printf("%d", MAX);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
#define PI 3.14
int main() {
printf("%.2f", PI);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int decimalVal = 42;
int octalVal = 052;
int hexVal = 0x2A;
printf("%d %d %d", decimalVal, octalVal, hexVal);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
double pi = 3.14;
printf("%.2f", pi);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
char letter = 'A';
printf("%c is %d", letter, letter);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers