How to declare a global variable inside a function?

I have a problem creating a global variable inside a function, this is a simple example:

int main{ int global_variable; //how to make that } 

This is exactly what I want to do:

 int global_variable; int main{ // but I wish to initialize global variable in main function } 
+6
source share
3 answers

You have two problems:

  • main not a loop. This is a function.

  • Your function syntax is incorrect. After the function name, you must have parentheses. Any of these are valid syntax for main :

     int main() { } int main(int argv, const char* argv[]) { } 

Then you can declare a local variable inside main as follows:

 int main() { int local_variable = 0; } 

or assign a global variable as follows:

 int global_variable; int main() { global_variable = 0; } 
+15
source

It is impossible to declare it the way you want. What is it.

But:

  • First, if you want, you can declare it before the body of main , but assign it a value inside main . Listen, Paul, answer that.
  • Secondly, there really is no advantage to declaring variables the way you want. They are global, which means that they must be announced globally and elsewhere.
+7
source
 int global_variable; int main() { global_variable=3; // look you assigned your value. } 
+5
source

All Articles