Function Definition in C, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 6.1 Free with a free account

Function Definition in C

Programming in C · Chapter 6: Functions, Scope, Storage Classes, and RecursionSection 6.1 · lesson 33 of 787 min · free with a free account

← Workshop: Summation, Factorial, and Input ValidationNext lesson: C Standard Library Overview →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Writing, declaring and calling functions in C, and the call stack.

  • Identify the return type, name, parameters and body of a function
  • Explain how arguments fill parameters by position
  • Write a prototype so the compiler knows a function before its first call
  • Describe how stack frames are pushed and popped during calls

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,034 words). Read along, or search it.

Opening Analogy

A Button for Each Job

Every arcade machine has buttons that each do one job: drop a token, print the tickets, play the jingle. Nobody rebuilds the ticket printer every time a player wins. They just press the button. A function is that button for your code. You build the job once, give it a name, and use it whenever you like.

Why Functions

One Banner, Two Calls

Say the welcome banner must print in two places. Copy the printf twice, and a name change means hunting down every copy. Instead, write the line once, inside a function called print_banner. Void in front means it hands nothing back; it only does a job. Void in the parentheses means it needs nothing from you either. To call a function, which means asking it to run, write its name followed by parentheses. Main calls it twice. Build and run. Two banners, from one definition. And notice that main is a function too. It's the one that runs first when the program starts. So functions give you three things: code you reuse, jobs with names that read like English, and small pieces you can test one at a time.

Anatomy

Return Type, Name, Parameters and Body

Many functions do more. Like a vending machine, they take values in, work something out, and send an answer back. Priya writes calc_prize, which turns a score and a bonus into prize tickets. Its first line is called the function header. First comes the return type: int, so a whole number comes back. Then the name. Then the parameters, each a new variable with its own type. The body, in braces, does the work. Return ends the function and sends one value back to the caller. In a call, the values in parentheses are arguments. 850 goes into score, and 10 into bonus: in order, by position. So the whole call acts like a number. You can store it, or use it in math, like plus 5 for a gift. Build and run. 850 over 100 is 8, plus 10 is 18. Then 37, and 8.

Prototypes

Declaring Before the First Call

But why does line 3 repeat the header, with a semicolon? Because the compiler reads your file from the top, like a recipe. At every call, it must already know the function's name, its parameters, and its return type. Line 3 is a prototype: a header, a semicolon, and no body. It's a promise that the function exists, and its body comes later. The part with the body, at the bottom, is the definition. You may promise a function many times, but define it only once. Watch what happens without the promise. Delete the prototype, and build again. Clang stops: call to undeclared function calc_prize. Very old C guessed silently, but C99 dropped that rule. GCC calls it an implicit declaration of the function. Same mistake, different wording. The fix is a prototype above main, or the whole definition there. And a prototype may leave out the parameter names. int calc_prize of int, int, is enough. It builds and runs again. So the rule is simple. The compiler must meet a function's name before the first call to it.

Common Mistake

A Path With No Return

One more slip: promising a value, and not delivering it. bonus_tier returns 5 only when the score is at least 1000. Below that, it reaches the closing brace with no return at all. Build and run. Clang warns: non-void function does not return a value in all control paths. It's only a warning, so the program still builds. This run is safe only because it passes 1500. With a lower score, using the result is undefined behavior: no answer you can trust. Treat this warning as a bug. Make every path return something, for example a final return 0.

Quick Check

Swapped Arguments in a Change Machine

Quick check. A change machine works out paid minus price. Main has a price of 3, and the player paid 10. What does this program print? Pause and predict. Build and run: change, minus 7. The first argument always goes into the first parameter, whatever its name. So price, which is 3, landed in paid. And paid, which is 10, landed in price. 3 minus 10 is minus 7. Names don't connect arguments to parameters. Only position does. And the compiler can't catch this, because both are ints.

Call Stack

Frames Pushed and Popped

What happens inside the computer when functions call functions? Think of a stack of plates at the snack bar. A new plate goes on top, and you can only take the top one off. The computer keeps a call stack the same way. Each plate is a stack frame: a block of memory holding one running function's parameters and local variables. Run it. The indentation shows how deep the calls go. Main starts, and its frame is the bottom plate. Main calls play_round, so a frame for play_round goes on top. It calls calc_prize, and a third frame lands on top of that. Each frame has its own variables. The score in play_round is a different box from the score in calc_prize. calc_prize returns 7, and its frame comes off. The answer goes back to the spot that called it. Then play_round finishes and its frame comes off, and finally main's.

Quick Check

Which Frames Are on the Stack

Quick check. When a player wins, celebrate calls jingle, and then lights. At the moment lights prints its line, which frames are on the stack? Pause and decide. Run it. Jingle prints first, then lights. While lights runs, the stack holds main, celebrate, and lights. Jingle's frame is already gone. It returned before lights was called, so its plate came off first. A frame lives only while its function is running, not just because it was called earlier.

Wrap-Up

Right Count, Wrong Places

Back at the arcade, Sam found a win that paid the wrong number of tickets. A printf inside calc_prize showed the bug. Two arguments in swapped order, just like the change machine. Right count, wrong places, said Sam. The compiler couldn't help, because both values were ints. Only reading the call against the header catches it.

Key Takeaways

Functions in Review

To sum up. A function header gives the return type, the name, and the parameters. Arguments fill the parameters by position, and return sends one value back. A prototype, or the definition, must come before the first call. And each call pushes a frame onto the stack; each return takes it off.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Function Definition in C

What are the parts of a function definition in C?
A function definition has a header and a body. The header gives the return type, the name, and the parameter list, each parameter with its own type, as in int calc_prize(int score, int bonus). The body, in braces, does the work, and return sends one value back to the caller. A return type of void means the function hands nothing back.
What is a function prototype in C and why is it needed?
A prototype is a function header followed by a semicolon, with no body, such as int calc_prize(int, int);. The compiler reads a file from the top and must know a function's name, parameter types and return type before the first call. Without a prototype or an earlier definition, clang reports a call to an undeclared function, because C99 removed implicit declarations.
How are arguments matched to parameters in C?
Arguments are matched to parameters by position, not by name. The first argument goes into the first parameter, the second into the second, and so on. If a function declared as int change(int paid, int price) returns paid - price but is called as change(price, paid) with price 3 and paid 10, it returns 3 - 10 = -7. The compiler cannot catch this when both are ints.
What happens if a non-void function does not return a value on every path?
The code still compiles, but clang warns that a non-void function does not return a value in all control paths. If the function reaches its closing brace without a return and the caller uses the result, the behavior is undefined, so the value cannot be trusted. Treat the warning as a bug and make every path return something, such as a final return 0.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →