Nearby lessons

73 of 124

C - Function Definition

The function definition is the function's actual body — the code that runs when it is called. Learn the full syntax, how local variables live inside it, and the rules for returning a value.

The Full Syntax

A definition is a header identical to the prototype, followed by a body in braces — and no semicolon:

Example01
CCode Cell
1#include <stdio.h>
2 
3int calculateTotal(int price, int quantity) /* header - no semicolon */
4{ /* body starts */
5 int total; /* local variable */
6 
7 total = price * quantity;
8 return total; /* send it back */
9} /* body ends */
10 
11int main()
12{
13 printf("5 items at 120 each = %d\n", calculateTotal(120, 5));
14 return 0;
15}
Output
5 items at 120 each = 600

Local Variables Live and Die with the Call

Variables declared inside a function exist only while it runs. Each call starts with a fresh copy:

Example02
CCode Cell
1#include <stdio.h>
2 
3void counter(void)
4{
5 int count = 0; /* created fresh on every call */
6 count++;
7 printf("count = %d\n", count);
8}
9 
10int main()
11{
12 counter();
13 counter();
14 counter(); /* always 1 - not 1, 2, 3 */
15 return 0;
16}
Output
count = 1
count = 1
count = 1

The return Statement

return does two things at once: it sends a value back and it exits the function immediately. Code after it never runs:

Example03
CCode Cell
1#include <stdio.h>
2 
3int findFirstNegative(int a[], int size)
4{
5 int i;
6 for (i = 0; i < size; i++)
7 if (a[i] < 0)
8 return i; /* exits the moment one is found */
9 
10 return -1; /* only reached if none found */
11}
12 
13int main()
14{
15 int a[5] = {3, 8, -2, 5, -7};
16 int b[3] = {1, 2, 3};
17 
18 printf("First negative in a: index %d\n", findFirstNegative(a, 5));
19 printf("First negative in b: index %d\n", findFirstNegative(b, 3));
20 return 0;
21}
Output
First negative in a: index 2
First negative in b: index -1

Every Path Must Return

If any branch can finish without a return, the caller receives garbage. Make sure a value comes back from every route:

Example04
CCode Cell
1#include <stdio.h>
2 
3/* BROKEN: negative input falls off the end
4int grade(int marks)
5{
6 if (marks >= 90) return 'A';
7 if (marks >= 75) return 'B';
8 if (marks >= 60) return 'C';
9} <- no return here
10*/
11 
12char grade(int marks) /* fixed with a final catch-all */
13{
14 if (marks >= 90) return 'A';
15 if (marks >= 75) return 'B';
16 if (marks >= 60) return 'C';
17 return 'F';
18}
19 
20int main()
21{
22 printf("95 -> %c\n", grade(95));
23 printf("80 -> %c\n", grade(80));
24 printf("40 -> %c\n", grade(40));
25 return 0;
26}
Output
95 -> A
80 -> B
40 -> F

void Functions

A void function returns nothing. You may still use a bare return; to leave early — a guard clause:

Example05
CCode Cell
1#include <stdio.h>
2 
3void printTable(int n)
4{
5 int i;
6 
7 if (n <= 0)
8 {
9 printf("Please give a positive number\n");
10 return; /* early exit, no value */
11 }
12 
13 for (i = 1; i <= 5; i++)
14 printf("%d x %d = %d\n", n, i, n * i);
15}
16 
17int main()
18{
19 printTable(-3);
20 printTable(7);
21 return 0;
22}
Output
Please give a positive number
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Returning Different Types

A function can return any single value type. To return several values, use pointers or a struct:

Example06
CCode Cell
1#include <stdio.h>
2 
3int getCount(void) { return 42; }
4float getAverage(void) { return 78.5f; }
5char getGrade(void) { return 'A'; }
6double getPrecise(void) { return 3.14159265; }
7 
8int main()
9{
10 printf("int : %d\n", getCount());
11 printf("float : %.1f\n", getAverage());
12 printf("char : %c\n", getGrade());
13 printf("double : %.8f\n", getPrecise());
14 return 0;
15}
Output
int    : 42
float  : 78.5
char   : A
double : 3.14159265

Where Definitions Can Go

Functions are defined at file level only. C does not allow nesting one inside another:

Example07
CCode Cell
1#include <stdio.h>
2 
3void helper(void) { printf("helper called\n"); }
4 
5int main()
6{
7 /* void inner(void) { } INVALID - no nested functions in C */
8 helper();
9 return 0;
10}
11 
12void afterMain(void) { printf("also valid\n"); }
Output
helper called

Type Conversion on Return

The returned value is converted to the declared return type. That silently truncates when types do not match:

Example08
CCode Cell
1#include <stdio.h>
2 
3int truncates(void) { return 3.99; } /* becomes 3 */
4float widens(void) { return 5; } /* becomes 5.0 */
5double divide(int a, int b)
6{
7 return (double) a / b; /* cast BEFORE dividing */
8}
9 
10int main()
11{
12 printf("truncates() = %d\n", truncates());
13 printf("widens() = %.1f\n", widens());
14 printf("divide(7, 2) = %.2f\n", divide(7, 2));
15 return 0;
16}
Output
truncates()   = 3
widens()      = 5.0
divide(7, 2)  = 3.50

Never Return a Local Array

A local array is destroyed when the function returns, so its address becomes invalid immediately. Have the caller supply the buffer instead:

Example09
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4/* BROKEN: buffer is gone the moment we return
5char *makeGreeting(void)
6{
7 char buffer[50];
8 strcpy(buffer, "Hello");
9 return buffer; <- dangling pointer
10}
11*/
12 
13void makeGreeting(char *out, size_t size) /* caller owns the memory */
14{
15 strncpy(out, "Hello from a function", size - 1);
16 out[size - 1] = '\0';
17}
18 
19int main()
20{
21 char message[50];
22 
23 makeGreeting(message, sizeof(message));
24 printf("%s\n", message);
25 return 0;
26}
Output
Hello from a function

Common Mistakes

MistakeResult
Semicolon after the headerBecomes a declaration; body is orphaned
Missing return on a pathCaller gets garbage
return value from voidCompiler error
Returning a local array's addressDangling pointer
Expecting a local to persistValue resets every call — use static
Defining a function twiceMultiple-definition linker error
Trainer's Note: the missing-return bug is quiet and dangerous. Compilers only warn if you ask, so build with -Wallwarning: control reaches end of non-void function catches it before your users do.
📝 Key Takeaways
  • A definition is the header plus a body in braces — no semicolon after it.
  • Local variables are created on entry and destroyed on return.
  • Every non-void path must return a value.
  • return with no value is used to exit a void function early.
  • A function cannot be defined inside another function in standard C.

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4