Bummer! You must be logged in to access this page.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Why declare a function before defining it?

In the section on functions in C, he declares the function at the top of the program, calls the function in the main() section, and then defines the function at the end. I tried declaring and defining the function prior to the main() section, and everything looks the same.

What is the purpose of declaring and then defining functions in different areas of the program?

1 Answer

if you dont declare a function prototype at the beginning, you must define it before using it or face undefined behavior. If you do declare a prototype, you can define it where ever, it doesnt have to be before you use it. This is because the prototype lets the compiler know necessary information about the function (return type, number and type of arguments etc). WIthout a prototype the compiler "guesses" these sorts of things which is where you encounter problems

The purpose of using a prototype and then defining it at the end seems more like a readability issue than anything to me. Its easier to keep all of your function definitions at the end of the file in one spot than have a function definition, call that function, do some other stuff, define another function, use it etc etc.