In C, we use functions as the basic unit of modular design. Modular design is the practice of designing a system in modules. A module is any entity with an interface and an implementation. The interface provides an abstraction (a simplified view of an entity which omits unimportant details) of the module.
An interface is a contract/intersection between the system and the environment. Credits: Robert Elder
Functions act as modules in C. The definition of the function determines the interface. Take for example the following:
#include <stdio.h>
void count_to(int number){
printf("Let's count from 1 to %d\n",number);
for (int i=1;i<=number;i++){
printf("%d\n",i);
}
}
int main(){
count_to(5);
count_to(10);
return 0;
}
By just typing count_to(number), we can use the function. This is the interface. The implementation is the actual body of the function. Appreciate how we do not need to know what the body of the function looks like in order to use it. We only need to know that we must pass an integer into the function.
Printf and scanf
Appreciate how we did not have to know what the bodies of the printf and scanf functions look like in order to use them to output information to and to accept inputs from the user.
The contract for printf says that in order to output a string onto the screen, you need to pass a string into the function. This string is a one-to-one representation of what is sent to the screen:
printf("This is a string and will be printed as is.\n");
The contract also says that if you have format specifiers in the string, you should, for each specifier, insert an extra argument in printf to tell the computer what to swap out in place of that corresponding format specifier. As long as we do these tasks, we can expect printf to output the correct string to the screen:
printf("This string has a format specifiers: %d %c %s\n",1,'A',"hello");
The contract for scanf is similar. We use a string containing format specifiers and include matching arguments for each specifier. The only difference compared to printf is that we use the ampersand (&) before the extra arguments in order to give scanf the addresses of the variables - strings are the exception because the name of the string is a pointer to the first character (thus already specifying the address):
char first_name[30];
float salary;
int age;
scanf("%d %f %s",&age,&salary,first_name);