just askking...WHY

line 6[Error] a function-definition is not allowed here before '{' token

1
2
3
4
5
6
7
8
9
10
  Put the code you need help with here.
#include<iostream>
using namespace std;
int main()
{
	int z()
	{
		cout<<"ok z";
	}
}
Function definitions are not allowed within other functions. What I think you want to do is:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;
int z() //This creates a function called z, that returns an integer and does what's inside the braces
{
	cout<<"ok z";

        return 1;
}
int main()
{ 
        int x = z(); //This calls z, and executes the code in it. Then, it returns the value of 1 to the caller, which is assigned to x.
        cout << x; //this will print '1'
}
Last edited on
int main() is a function.
Everything between int main(){ and its closing bracket } is part of the implementation of that function.

This:
1
2
3
4
int z()
{
      cout << ""ok z";
} 

is the function definition of a function called z(). Your problem is that it is placed inside the brackets of the main function.

You are not allowed to define a function inside a function (except for lambda functions, but I think that is for later).

To fix your problem you should move the defintion of function z() outside of the main function.
Subsequently you will have to fix the function z(), because the function header "int z()" indicates that this function will return an integer value. At present the function doesn't return anything (void). If you are happy with the function as it is now, you should change the function header to "void z()". If you want function z to return an integer value, you should add returning that value just before the closing bracket.

If you moved the function below the main function, you will have to add an additional function declaration above the main function (because otherwise the compiler doesn't notice it in time), if you placed the function above the main function you don't need to do this.

Finally, you have to add a function call to function z() in the main function, or it will never be used.

I think your code should end up looking something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>

using namespace std;

int z(); // added function declaration to let the compiler know it exists.

int main()
{
    z();    // function call, this is where the function z() is called (note that you don't mention the return type here).
    system("pause");    // wait for the user to press a key, so we can see the result
}

int z()     // function implementation is defined OUTSIDE any other function.
{
    cout<<"ok z";
    return 42;
}


Kind regards, Nico
that's a very clear answers...you save my day....apreciate that
Topic archived. No new replies allowed.