Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

C Functions

C Functions

A function is a segment of code that executes only upon invocation.

It accepts input data, referred to as parameters.

Functions serve to execute specific tasks and are vital for code reuse: Define the logic once and employ it repeatedly.

Predefined Functions

Indeed, it appears you’re already familiar with the concept of a function. Throughout this tutorial, you’ve been utilizing functions consistently.

As an illustration, “main()” serves as a function responsible for executing code, while “printf()” functions to output or print text onto the screen.

Example

int main() {
  printf(“Hello World!”);
  return 0;

Create a Function

To create, commonly referred to as declare, your own function, indicate the function name, followed by parentheses () and curly brackets {}.

Syntax

void myFunction() {
  // code to be executed
}

Example Explained

  • The functin iso named myFunction().
  • “void” indicates that the function does not return a value. Further details about return values will be covered in the upcoming chapter.
  • Within the function body, include code that specifies the actions the function should perform.

Call a Function

Declared functions are not executed immediately. Instead, they are “stored for later use” and will be executed only when they are called.

To invoke a function, simply write the function’s name followed by two parentheses () and a semicolon ;

In the given example, myFunction() is employed to print a text (the action) upon its invocation.

Example

Within the main function, invoke myFunction().

// Create a function
void myFunction() {
  printf(“I just got executed!”);
}

int main() {
  myFunction(); // call the function
  return 0;
}

// Outputs “I just got executed!”

A function can be invoked multiple times.

Example

void myFunction() {
  printf(“I just got executed!”);
}

int main() {
  myFunction();
  myFunction();
  myFunction();
  return 0;
}

// I just got executed!
// I just got executed!
// I just got executed!