C Programming/Functions

Completion status: this resource has reached a high level of completion.

Objective

edit
  • Familiarise yourself with functions
    • How to define them
    • How to invoke them
    • Prototyping

Introduction to functions in C

edit

In today's world we believe that Time is Money. The less time you spend in writing a program, the more efficient use of resources. Functions helps a programmer avoid rewritting code over and over, even more so than looping, and hence save time, cost, and effort.

Let's say we would like to write a program that calculates the square of a number. The application that we are asked to design requires that you calculate the square of several numbers again and again. So, you will write the following code to calculate the square of the number wherever needed.

int result;
result = a * a;

If you have to calculate the square of the number at 3 different places in your program, you will have to write these lines of code over and over again.

int main(void)
{
     ... 
     result = a * a; 
     ... 
     result = b * b;
     ... 
     result = c * c;
     ... 
     return 0;
}

Luckily, we do not need to do this, because C, like most programming languages, allows us to declare functions. A function is named a block of code that, when invoked, is executed. This is what a function definition looks like:

returntype name(parameters ...)
{
     statements ...
}

A C function may specify any primitive type or a struct (a special C type that will be explored further in a later lesson) as its return type, or void if the function does not return anything. Functions with void as a return type is also termed procedures, which is old-fashioned nowadays (the term procedures is still used in Pascal). If a function defines a return type, it must return a variable, constant, or literal of that type before the function-closing } is encountered, or a compiler error will occur. A function definition must also specify its parameters, a list of comma-separated variable declarations, or void if it does not have any parameters. If a function does not specify any parameters, then its parameter list is implicitly void, and does not need to be declared as such. Here is a C function that calculates the square of an integer n:

int square(int n)
{
     int ans = n * n;
     return ans;
}

Once a function has been defined, we can now use this function wherever we would like to use it. For example:

int main()
{
     ...
     result = square(a); 
     ...
     result = square(b);
     ... 
     result = square(c);
     ...
     return 0;
}

Thus, instead of writing the entire code over and over again, we can simply call the function here.

It's also important to note that whitespace is ignored - so the following snippets are all the same:

int func_name(void){}
int func_name(void)
{
}
int func_name (void) {
}


Each of these snippets incorporating elements of possible styles for writing C code. The main thing to note about whitespace is it only matters when it would be between two different things which could then make a single "symbol" (a symbol is a name representing a certain value - be it a function/function location or a variable). With proper syntax in all other ways, this only can cause problems when declaring variables/functions, or when casting. Just remember to place some whitespace between each specifier, qualifier, modifier, the type and the symbol name (specifiers, qualifiers and modifiers explained in that page). Programmers prefer to use a space, but these have the same meaning:

int x=1
int
x	=

1

Function prototype

edit

A function prototype or function interface is a declaration of a function that specifies the function’s name and type signature (data types of parameters, and return type), but omits the function body.

#include <stdio.h>

int addTwoNumbers(int a, int b);//This is function prototype

int main () {
    printf("Add 2 number: %d \n", addTwoNumbers(3, 4));
}

int addTwoNumbers(int a, int b){
    return a+b;
}

Functions are the backbone of any C algorithm. All C data types can be passed to a function, even with an array (if passed they will be converted to pointers, which will be discussed in later lesson) or function (as callback function), and all may be returned.

Functions can also call other functions:

int multiply_together(int n1, int n2)
{
     return n1 * n2;
}

int add_two_and_multiply(int n1, int n2)
{
     n1 = add_two(n1);
     return multiply_together(n1, add_two(n2));  /* returns (n1 + 2) * (n2 + 2) */
}

Function arguments as void: A function with no parameter can accept a void.

#include <stdio.h>

int returnNumber(void){
   return 5;
}
int main () {
   printf("returnNumber: %d \n", returnNumber());//returnNumber: 5

}

main() function

edit

main(), the center of every C program, can have many forms:

int main(){}
int main(void){}
int main(int argc, char **argv){}
int main(int argc, char **argv, char **envp){} //Note that this syntax is not specified in POSIX, but is used by all three main OSes.

GCC compiler expects main() to return an int. If the code finishes with no problems, main() should return 0. Otherwise, it should return some other value - normally 1. The syntax for a main() function that simply returns 0 is:

int main(void)
{
  return 0;
}

Command line arguments with main()

edit
int main( int argc, char *argv[] ){}

It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments.

  • argc: number of arguments passed
  • argv[]: pointer array which points to each argument passed to the program

Example

#include <stdio.h>

int main(int argc, char *argv[])  {
    printf("argv[0]: %s \n", argv[0]);
    printf("argv[1]: %s \n", argv[1]);
    printf("argv[1][0]: %c \n", argv[1][0]);
    printf("Total argument: %d", argc);
}

Input: ./a.out Hello

Output

argv[0]: ./a.out 
argv[1]: Hello
argv[1][0]: H
Total argument: 2

To enter a string in *argv[], use \:

Input: ./a.out Hello,\ World\ !

Output

argv[0]: ./a.out 
argv[1]: Hello, World !
Total argument: 2

Assignments

edit

Converts the given Fahrenheit temperature to Celsius: fahrenheit_to_celsius.c (Source code from the Programming Fundamentals course)