Why am I getting a function definition error in my C++ code?

September 13, 2025 3 answers
Asked by CoderGal123
I'm a beginner programmer trying to learn C++, and I'm stuck on a function definition error I'm encountering on HackerRank. Here's the code I wrote: ```cpp int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int max_of_four(int a, int b, int c, int d) { int max = 0; if (max <= a) { max == a; } if (max <= b) { max == b; } if (max <= c) { max == c; } if (max <= d) { max == d; } return max; } return 0; } ``` I'm receiving the following error message: ``` Solution.cpp: In function 'int main()': Solution.cpp:11:48: error: a function-definition is not allowed here before '{' token int max_of_four(int a, int b, int c, int d) { ^ ``` I'm confused because I thought I was correctly defining my function. I did some research and it seems to relate to the braces, but I couldn't pinpoint the issue. Any insights would be greatly appreciated!

Answers

DevDude15
You really can't define a function inside another in C++. Move your `max_of_four` function outside of `main`, and it should compile. Also, just so you know, functions can be defined inside other functions using lambdas since C++11, but that's not what's happening here.

CoderGal123: Got it! Iโ€™ll make the changes. Lambdas sound fascinatingโ€”I'll definitely explore that when I'm more comfortable with the basics!

Reply to this answer
TechieTom92
The error happens because in C++, you can't define a function inside another function. Your `max_of_four` function needs to be defined outside of `main`. The HackerRank template suggests putting the `max_of_four` function in the top-level, not inside `main`. Fixing that should solve your issue!

CoderGal123: That makes total sense! I didn't realize `main` is a function too, which is why I didnโ€™t think about the placement. Thanks for the clarification!

Reply to this answer
CPlusPlusNinja
Just a heads-up, donโ€™t mix up `=` and `==`. One is used for assignment, and the other for checking equality. Once you sort out the function placement, this shouldn't be a problem for you anymore!

CoderGal123: Haha, I appreciate the reminder! That type of mistake often trips me up, so Iโ€™ll keep that in mind as I fix it!

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions