TThom246
TThom246

Reputation: 13

Calling functions within another function

I am writing a program. And in the main function "int main()" i call to a function called, lets say, "int X()". Inside "int X()" I would like to call to another function "void Y()". Any ideas how to do this? I tried, inside the X() function, doing "Y();" and "void Y();" but to no prevail. Any tips on getting this to work? if at all possible?

ex.

#include<iostream>

int X()
{
   Y();
}

void Y()
{
   std::cout << "Hello";
}

int main()
{
   X();
   system("pause");
   return 0;
}

Upvotes: 1

Views: 62135

Answers (5)

Vladimir Grigorov
Vladimir Grigorov

Reputation: 1

You need to have cout << X(); X() it's just for void function!

Upvotes: 0

3yakuya
3yakuya

Reputation: 2672

You must define or declare your functions before you use them. For example:

void Y();         //this is just a declaration, you need to implement this later in the code.
int X(){
    //...
    Y();
    //...
    return someIntValue;   //you will get warned if function supposed to return something does not do it.
}

OR

void Y(){
    //code that Y is supposed to do...
}

int X(){
    //...
    Y();
    //...
}

When you call the function you do not write its type anymore (to call functon Y you write: Y(arguments); and not void Y(arguments);). You write the type only when declaring or defining the function.

Upvotes: 3

Shoe
Shoe

Reputation: 76240

When the compiler reaches:

int X()
{
   Y();
}

it doesn't know what Y is. You need to declare Y before X by inverting their declarations:

void Y()
{
   std::cout << "Hello";
}

int X()
{
   Y();
}

int main()
{
   X();
   system("pause");
   return 0;
}

You should also provide a return value for X, otherwise a warning will pop up.

And please, don't follow the suggestion of using using namespace std;. The way you writing std::cout is just fine.

And here is the working example.

Upvotes: 2

user2345215
user2345215

Reputation: 637

You need to declare the Y function before the X function uses it.

Write this line before the definition of X:

void Y();

Upvotes: 1

marcinj
marcinj

Reputation: 49986

You must declare Y() before using it:

void Y();

int X()
{Y();}

Upvotes: 6

Related Questions