C Tutorial menu

C Functions

A function is a block of code with a name. You write it once and call it whenever you need it.

Creating and Calling a Function

Example

c
#include <stdio.h>

void welcome(void) {
  printf("Welcome to Workownix!\n");
}

int main(void) {
  welcome();
  welcome();
  return 0;
}
Output
Welcome to Workownix!
Welcome to Workownix!

void before the name means the function returns nothing. void inside the brackets means it takes no parameters.

Parameters and Return Values

Example

c
#include <stdio.h>

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

double discount(double price, double percent) {
  return price - price * percent / 100;
}

int main(void) {
  printf("%d\n", square(6));
  printf("%.2f\n", discount(2000, 15));
  return 0;
}
Output
36
1700.00
PartExampleMeaning
Return typeintType of the value sent back
NamesquareHow you call the function
Parameters(int n)Values the function receives
returnreturn n * n;Sends the result back and ends the function

Function Prototypes

C reads your file from top to bottom. If you call a function before it is written, add a prototype (a declaration) at the top:

Example

c
#include <stdio.h>

int add(int a, int b);   // prototype

int main(void) {
  printf("Total: %d\n", add(450, 300));
  return 0;
}

int add(int a, int b) {  // definition
  return a + b;
}
Output
Total: 750

In bigger projects, prototypes go in a header file (.h) and the definitions go in a .c file. This is how stdio.h gives you printf.

Passing by Value

C passes a copy of each argument. Changing the parameter inside the function does not change the original variable:

Example

c
#include <stdio.h>

void tryChange(int x) {
  x = 100;
}

int main(void) {
  int score = 5;
  tryChange(score);
  printf("%d\n", score);
  return 0;
}
Output
5

To change the original, you pass its address with a pointer. You will see this in the next chapter.

Scope

  • A local variable is created inside a function and only exists there
  • A global variable is created outside all functions and can be used everywhere

Prefer local variables. Too many globals make programs hard to follow.

Recursion

A function that calls itself is recursive. It must have a stopping case:

Example

c
#include <stdio.h>

int sumTo(int n) {
  if (n == 0) {
    return 0;          // stopping case
  }
  return n + sumTo(n - 1);
}

int main(void) {
  printf("%d\n", sumTo(5));   // 5+4+3+2+1
  return 0;
}
Output
15

Useful Built-in Functions

HeaderFunctions
<stdio.h>printf, scanf, fgets
<string.h>strlen, strcpy, strcmp
<math.h>sqrt, pow, fabs (add -lm when compiling on Linux)
<stdlib.h>abs, rand, malloc, free

Exercise

Exercise

Why do we write a function prototype at the top of a C file?

Learn C with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp