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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: C Standard Library Overview →← Workshop: Summation, Factorial, and Input ValidationNext lesson: C Standard Library Overview →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is a function prototype in C and why is it needed?
How are arguments matched to parameters in C?
What happens if a non-void function does not return a value on every path?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →