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 Function Declaration

Function Declaration and Definition

You’ve just learned from the preceding chapters how to create and invoke a function as follows:

Example

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

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

A function comprises two components:

  • Declaration: Includes the function’s name, return type, and parameters (if any).
  • Definition: Encompasses the body of the function, containing the code to be executed.
void myFunction() { // declaration
  // the body of the function (definition)
}

For enhanced code optimization, it’s advisable to segregate the declaration and definition of functions. It’s a common practice in C programming to place function declarations above the main() function and function definitions below it. This promotes better code organization and readability:

Example

// Function declaration
void myFunction();

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

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

Another Example

If we refer back to the example provided in the preceding chapter regarding function parameters and return values:

Example

int myFunction(int x, int y) {
  return x + y;
}

int main() {
  int result = myFunction(5, 3);
  printf(“Result is = %d”, result);
  return 0;
}
// Outputs 8 (5 + 3)

Writing it in the following manner is considered good practice:

Example

// Function declaration
int myFunction(int, int);

// The main method
int main() {
  int result = myFunction(5, 3); // call the function
  printf(“Result is = %d”, result);
  return 0;
}

// Function definition
int myFunction(int x, int y) {
  return x + y;
}