Skip to main content

7. Format Specifier, Escape Sequences and Constants in C

 

Format Specifier

Format specifier is a way to tell the compiler what type of data is in a variable during taking input and displaying output to the user. Ex: %c, %d, %f etc.

printf("My phone's battery is %x.yf", var); will print var with y decimal points in x character space.
If the value of x is positive and greater than the character value in var, then extra value of x will be expressed as space before the floating number. If the value of x is negative, then x space bars will be expressed after the floating number.

Escape Sequences in C

An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.
It is composed of two or more characters starting with backslash \. For example : \n represents a new line.

List of Escape Sequences in C

Escape SequencesMeaning
\aAlarm or Beep
\bBackspace
\fForm Feed
\nNew Line
\rCarriage Return
\tTab(Horizontal)
\vVertical Tab
\\Backslash
\'Single Quote
\"Double Quote
\?Question Mark
\nnnOctal Number
\xhhHexadecimal Number
\0Null

#include <stdio.h>

int main()
{
   printf("You\nare\nlearning\n\'C\' language\n\"Do you know C language\"");
   return 0;
}

Output :

You
are
learning
'C' language
"Do you know C language"

Constants in C

A constant is a value or variable that can't be changed in the program.
There are different types of constants in C programming.

List of Constants in C

ConstantExample
Decimal Constant10, 20, 450 etc.
Real or Floating-
point Constant
10.3, 20.2, 450.6 etc.
Octal Constant021, 033, 046 etc.
Hexadecimal
Constant
0x2a, 0x7b, 0xaa etc.
Character Constant'a', 'b', 'x' etc.
String Constant"c", "c program" etc.

How to define a Constant in C

There are two ways to define constant in C programming.

1. const Keyword

The const keyword is used to define constant in C programming.

#include <stdio.h>

int main()
{
const float PI = 3.14;

printf("The value of PI is : %f\n", PI);
return 0;
}

Output :

The value of PI is : 3.140000

If we try to change the value of PI, it will render compile time error.

2. #define preprocessor

The #define preprocessor is also used to define constant.

#include <stdio.h>
#define PI 3.14

int main()
{
 printf("The value of PI is : %f\n", PI);
 return 0;
}

Output :

The value of PI1 is : 3.140000

Comments