C Functions

What is a Function?

A function is a block of code that performs a specific task.

Functions help organize code, reduce repetition, and make programs easier to understand.

Loading...
Output:

Function Declaration (Prototype)

A function prototype tells the compiler about a function before it is used.

It defines the function name, return type, and parameters.

Loading...
Output:

Function Definition

The function definition contains the actual code that runs.

Loading...
Output:

Calling a Function

You call a function by using its name followed by parentheses.

Loading...
Output:

Parameters and Arguments

Parameters are variables defined in the function, while arguments are the values passed to it.

Loading...
Output:

Return Values

Functions can return values using the return statement.

The return type must match the function declaration.

Loading...
Output:

Void Functions

If a function does not return a value, use void.

Loading...
Output:

Passing Arrays to Functions

Arrays are passed to functions as pointers.

This means changes inside the function affect the original array.

Loading...
Output:

Pass by Value vs Pointer

C uses pass-by-value by default, meaning a copy is passed.

To modify the original value, use pointers.

Loading...
Output:

Why Functions are Important

Functions are essential for writing clean and reusable code.

  • Reduce repetition
  • Improve readability
  • Make debugging easier

Common Mistakes

Be careful with these:

  • Forgetting function prototypes
  • Mismatched return types
  • Not using pointers when needed

Practice

Create a function that takes two integers and returns their sum.

Loading...
Output:

Need Help?