HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

C Functions



C functions are fundamental building blocks in C programming. They encapsulate a set of instructions that perform a specific task and can be reused throughout your code.

One of their key features is the ability to accept data from the outside world through parameters.

Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.


Predefined Functions

Predefined functions, also known as library functions or standard library functions, are a set of functions readily available for use in your C programs. They are pre-written and compiled, saving you the time and effort of implementing them yourself. These functions come from standard C libraries like stdio.h, math.h, string.h, and more.

For example, main() is a function, which is used to execute code, and printf() is a function; used to output/print text to the screen:

Example

#include <stdio.h>

int main() {

printf("Hello CodeLines!");

return 0;

}

Optput

CodeLines


Create a Function

To create (often referred to as declare) your own function, specify the name of the function, followed by parentheses () and curly brackets {}:

Example

void myFunction() {

// code to be executed

}


Example Explained


myFundanction() is the name of the function

void means that the function does not have a return value. You will learn more about return values later in the next chapter

Inside the function (the body), add code that defines what the function should do


Call a Function

Declared functions are not executed immediately. They are "saved for later use", and will be executed when they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:


Example

Inside main, call myFunction():

#include <stdio.h>

int main() {

// Create a function

void myFunction() {

printf("I just got executed!");

}

int main() {

myFunction(); // call the function

return 0;

}

Optput

I just got executed!

A function can be called multiple times:


Example

#include <stdio.h>

int main() {

// Create a function

void myFunction() {

printf("I just got executed!\n");

}

int main() {

myFunction(); // call the function

myFunction(); // call the function

myFunction(); // call the function

return 0;

}

Optput

I just got executed!

I just got executed!

I just got executed!