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

0
1
Asked By CoderGal123 On

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!

3 Answers

Answered By CPlusPlusNinja On

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!

Answered By TechieTom92 On

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!

Answered By DevDude15 On

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!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.