Is it a good idea to put variables outside the main() function?

Hello, I’m currently trying to practice programming functions in C++. I was wondering if it would be a good idea to type variables outside of the main() function. I don’t know if you can use variables from the main() function to another function. If anyone can answer my question I would appreciate it. Thank you!

How long have you been learning c++? Normally you shouldn’t declare your variables outside of the main function, only other functions.

I would guess that since you’re calling the function within main(), then the function (even if it is defined outside of main() ) should be able to access it

Declaring variables as global is not recommended. Imagine you are making a game where there are a lot of characters and you define health as global variable. You will get confused really soon. Might not be the best example but hope you get my idea.
A better way to access variables is using function parameters.

Here’s an example:

int takeDamage(int health, int damage){ return health - damage; } void character1(){ int health = 10; health = takeDamage(health, 1); } void character2(){ int health = 10; health = takeDamage(health, 2); } int main(void){ character1(); character2(); return EXIT_SUCCESS; }

It improves the readability of your code in general.

There are also a few points I selected from Why should we avoid using global variables in C/C++?

Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use.

Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.