C - printf function Introduction

Introduction

Consider the code

//Using a variable
#include <stdio.h>

int main(void)
{
      int salary;           // Declare a variable called salary
      salary = 10000;       // Store 10000 in salary
      printf("My salary is %d.\n", salary);
      return 0;
}

printf("My salary is %d.\n", salary) has two arguments inside the parentheses, separated by a comma.

The two arguments to the printf() function are:

  • the first argument is a control string
  • the second argument is the name of the variable, salary.

The control string in the first argument determines how the value of salary will be displayed.

The control string contains some text to be displayed.

%d embedded is called a conversion specifier for the value of the variable.

Conversion specifiers determine how variable values are displayed on the screen.

They specify how to convert the value before it is displayed.

In this case, you've used a d, which is a decimal specifier that applies to integer values.

It means that the second argument, salary, will be represented and output as a decimal (base 10) number.

Note

Conversion specifiers always start with a % character.

You must use the escape sequence %% when you want to output a % character.

Conversion Characters

Conversion
Character
What It Displays

%%
Percent character (%)
%c
Single character (char)
%d
Integer value (short, int)
%e
Floating-point value in scientific notation using a little E (float, double)
%E
Floating-point value in scientific notation using a big E (float, double)
%f
Floating-point value in decimal notation (float, double)
%g
Substitution of %f or %e, whichever is shorter (float, double)
%G
Substitution of %f or %E, whichever is shorter (float, double)
%i
Integer value (short, int)
%ld
Long integer value (long int)
%o
Unsigned octal value; no leading zero
%p
Memory location in hexadecimal (*pointer)
%s
String (char *)
%u
Unsigned integer (unsigned short, unsigned int, unsigned long)
%x
Unsigned hexadecimal value, lowercase (short, int, long)
%X
Unsigned hexadecimal value, capital letters (short, int long)

Related Topics