Computer Science

C Program — Functions & Pointers

2023-08-13 2 min read

Function

Functions

A function is a block of code which only runs when it is called. Functions are used to perform certain actions, and they are important for reusing code: define the code once and use it many times.

We can broadly divide functions into two kinds:

  • those that return a value
  • those that don’t return a value

Advantage

A function is how we put procedure abstraction into practice:

  • Reusability
  • Readability
  • Reduce coupling — coupling is how much a piece of code depends on other code.
  • Modularity of the program

Syntax _ return value

Syntax _ without parameter

Syntax _ without return value

Function

Think of a function as the realization of one capability. It simplifies main, cleanly separates responsibilities, achieves reuse and lower coupling, and lets you write and reason about the program one block at a time.

At first you can ignore how the function is implemented and just trust that it does its job. Once the pieces are separated, you then work out — block by block — how to write the code inside each function to get the behavior you want.

Pointer

Recall

DataType  variableName  =  data;

Value

Pointer

Declare

  • T* ptr ptr points to a T-type object/value.
  • &value get the address of value.
  • *ptr access the data at an address.

Pointer

Pointer in Pointer

Pointer and Array

Thinking

What does the program below output?

← Posts
meow~