C Language | Introduction to C | Constants

This article explains how to write fixed values such as numbers and characters in source code.

Suffixes

Fixed values such as 100 and string literals are called constants. Numeric constants are divided into integer and floating-point constants. An integer without a suffix is normally treated as an int, while a value with a decimal point is treated as a double.

Use a suffix to specify another type.

Table 1 - Integer suffixes

Suffix Type Example
l or L long int or unsigned long int, depending on the value 123456789L
u or U unsigned int or unsigned long int, depending on the value 123456789U
l or L with u or U unsigned long int 123456789UL

Table 2 - Floating-point suffixes

Suffix Type Example
f or F float 3.14F
l or L long double 3.14L

Code 1

#include <stdio.h>

int main() {
 float fVar = 3.14F;
 printf("%g\n" , fVar);
 return 0;
}

The F suffix explicitly marks 3.14F as a float.

Writing Constants in Different Forms

Floating-point constants may use exponent notation. The following values all represent 3.14.

Code 2

#include <stdio.h>

int main() {
 float fVar1 = .314e1F;
 float fVar2 = 314e-2F;
 float fVar3 = 31.4e-1F;
 printf("fVar1 = %g\nfVar2 = %g\nfVar3 = %g\n" , fVar1 , fVar2 , fVar3);
 return 0;
}

Integer constants may be written in decimal, octal, or hexadecimal notation. Prefix an octal value with 0, and prefix a hexadecimal value with 0x or 0X.

Code 3

#include <stdio.h>

int main() {
 printf("0xFF = %d\n0377 = %d\n" , 0xFF , 0377);
 return 0;
}

Both 0xFF and 0377 represent decimal 255.

Character Constants

A character constant is written in single quotes, such as 'A'. Characters are handled as numeric codes. In ASCII, 'A' is 0x41, 'B' is 0x42, and 'C' is 0x43.

Code 4

#include <stdio.h>

int main() {
 char chVarA = 'A';
 char chVarB = 0x42;

 printf("chVarA(%%X) = %X\nchVarA(%%c) = %c\n" , chVarA , chVarA);
 printf("chVarB(%%X) = %X\nchVarB(%%c) = %c\n" , chVarB , chVarB);
 return 0;
}

A string literal such as "A" and a character constant such as 'A' are different types of values.

Escape Sequences

Strings and character constants can contain escape sequences that begin with a backslash.

Table 3 - Escape sequences

Sequence Meaning
\a alert
\b backspace
\f form feed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\? question mark
\' single quote
\" double quote
\0 null character
\N octal value
\xN hexadecimal value

Escape sequences are useful for characters that are difficult or impossible to type directly, such as a newline, a tab, or a quote inside a literal.