How to create a function in ‘C’

TheDevStory
2 min readOct 30, 2022

c language

How can we make the function in ‘C’?

Main function

we can use main() for using function. main() mean start the program in C.

#include <stdio.h>void main(){  printf ("Hello, World!");}

Void

The Void means the function doesn’t have any return value. if you want to add a return. And after that, you can change the void to others.

Return something

for example, if you want to return int value…

int Sum (int value1, int value2){  int result = value1 + value2;  return result;}

Using Caller

C is an assembly of functions. That means you can use various functions in a single program. The Caller is a function that calls other functions from outside of him.

#include <stdio.h>int Sum (int value1, int value2) {  return value1 + value2;}void main(void) {  int a = 1;  int b = 2;  int c = Sum(a, b);  printf("Sum of %d and %d is %d \n", a, b, c);}

Function Prototype

C compute top to bottom. That means if you do not declare the function first, you will get an error.

/* error example */void main(void) {int a = 1;int b = 2;int c = Sum(a, b); /* ERROR! : can't find Sum() */printf("Sum of %d and %d is %d \n", a, b, c);}int Sum (int value1, int value2) {return value1 + value2;}return value1 + value2;}

In this situation, you can use a function prototype, like below.

int Sum (int value1, int value2); 
/* without declare 'Sum' first, you'll get an error. */
void main(void) { int a = 1; int b = 2; int c = Sum(a, b); printf("Sum of %d and %d is %d \n", a, b, c);}int Sum (int value1, int value2) { return value1 + value2;}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

TheDevStory
TheDevStory

Written by TheDevStory

A web developer crafting online experiences. Also football(soccer) coach and Spanish Learner.

Responses (1)

Write a response