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 trialPeter Escartin
893 PointsBreaking down the function lesson
I'm on this lesson and had some questions: refer to the code below
int funky_math( int a, int b); //Why is this being declared here and not in main? Do all functions need to be declared before main?
int main()
{
int foo = 24; \\ Is foo and bar the int a & int b in funky_math?
int bar = 35;
printf("funky math %d\n", funky_math(foo, bar));
return 0;
}
int funky_math(int a, int b) // int a is 24 and int b is 35?
{
return a + b + 343;
}
Overall the implementation of functions and declaring them is a bit fuzzy, does anyone have a more clear way to explain it?
2 Answers
Ben Hopkins
Full Stack JavaScript Techdegree Student 2,348 PointsHi Peter,
Yes, all functions should be declared outside of the main function, then implemented within it.
Is foo and bar the int a & int b in funky_math? - Basically no.
What is happenning here is three things:
Firstly, the function is being declared before main. This just states that funky_math is a function returning and integer, which takes two arguments, bothare also integers.
Second, the function is being defined after the main function. Here you have explained in code what the function will do with the two arguments passed to it. in this case add them together, then add 343.
Finally, you are using the function within the main function. Here you pass funky_math the two variables you have defined (foo and bar), and printf the result.
Note: you could pass funky_math any two integers, some examples below:
funky_math(10,7);
//This would return 360 (10+7+343)
int alpha = 17;
int beta = 50;
funky_math(alpha,beta);
//This would return 410 (17+50+343)
funky_math(1,alpha);
//This would return 361 (17+1+343)
Let me know if you have any further questions! I hope this has helped!
Peter Escartin
893 PointsThis is great! Thanks for explaining that for me!
Matthew Mascioni
20,444 PointsMatthew Mascioni
20,444 PointsSweet answer, Ben Hopkins!