-1

What is the exact use of % in scanf and printf? And would scanf and printf work without the % sign? All I could find is that % is the conversion specifier but I want to know how it works actually?

ani627
  • 5,578
  • 8
  • 39
  • 45
sunny
  • 13
  • 2

3 Answers3

2

% is simply the symbol used to identify the beginning of a conversion specifier in the format string; why % as opposed to any other symbol is an open question, and probably doesn't have that interesting an answer. The printf and scanf functions search the format string for conversion specifiers to tell them the number and types of additional arguments to expect, and how to format the output (for printf) or interpret the input (for scanf).

To print a literal %, you need to use %%.

printf can work without using a conversion specifier, but you'll be limited to writing literal strings. scanf is pretty useless without it.

John Bode
  • 119,563
  • 19
  • 122
  • 198
1

The '%' character is used in the format string of the scanf() and print()-like functions from the standard header <stdio.h>, to indicate place holders for variable data of several kinds. For example, the format specifier "%d" is a place holder for a value having type int.

Thus, the variadic function printf() expects additional parameters passed as arguments to the function, the first of them having type int.

The value of this int argument is converted to string, and it will be replace to the place holder "%d".

In the case of scanf(), the situation is similar, but now scanf() is an input function that expects that the user enters in command-line a value fitting on the type indicated by the format specifier. Thus, a format specifier "%d" will expect that the user enters a value of type int.

Since all the arguments in C are passed by value, the input data requires you use the address of the variable, to mimic a by-reference mode of passing arguments.

There are a lot of options and details related to these format specifiers.
Yo need to take a look at the bibliography.
For example, start in Wikipedia:

printf() format string
scanf() format string

pablo1977
  • 4,281
  • 1
  • 15
  • 41
1

The % in a scanf() or printf() is a keyword whose purpose is identify the type of data that will be stored in the named variable. So, in the following example, the compiler would build instructions to accept input data of type integer and store it in the memory location at the address assigned to num1:

int num1;
scanf("%d",&num1);
clcto
  • 9,530
  • 20
  • 42