• ### Announcements

• #### Wondering what's new and changed at GameDev.net?06/20/17

Check out the latest Staff Blog update that talks about what's changed, what's new, and what's up with these "Pixels".
Followers 0

# C++ Functions run when I don't want them to

## 16 posts in this topic

I want to make a function in main that will not run however just making the function causes it to run

I tried prototyping the function but I am using object that are made and in main and that is out of scope
That goes the same for above main, as the variables/objects inside were defined in main
How do I stop the program from running the function without calling it when I create it?

0

##### Share on other sites

My program has SFML so I am not going to post that code but here is simple version of what I mean

#include <iostream>

using namespace std;

int main()
{
void function();
{
cout << "Hello world!" << endl;
}

return 0;
}



The program will say Hello World

but I want it to only run when i call the function later on

How do I stop that?

0

##### Share on other sites

I see my issue now, I haven't coded in a long time but I can't believe I made such a basic mistake

Thanks everyone but I have a new issue related to my original issue

How do I make a function that can work with a variable declared in the main?

#include <iostream>

using namespace std;

void function();

int main()
{
int x = 5;

return 0;
}

void function()
{
cout << x << endl;
}



I get an error at second last line saying x is out of scope, I understand why I just don't know how to solve this

0

##### Share on other sites

I try not to use classes in C++ because of how functions are called by themself. C style object orientation is more flexible using structs, virtual function tables and separate methods.

Before it was called C++, it was called "C with Classes".

0

##### Share on other sites

Before it was called C++, it was called "C with Classes".

I used to be called a baby. That was 20+ years ago.
2

##### Share on other sites

Wow. It was a pretty ignorant comment, but -21 is pretty harsh for the beginner's forum. Let's calm down a little, lol.

1