Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare global variable inside function?

I have problem creating global variable inside function, this is 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
}
like image 859
user3137147 Avatar asked Dec 30 '13 20:12

user3137147


People also ask

How do you set a global variable in a function?

To globalize a variable, use the global keyword within a function's definition. Now changes to the variable value will be preserved. In the snippet below, a is globalized and b is not. Subsequently, the change to a is kept, while b remains as the original value prior to the function's execution.

Can I declare a global variable inside a function in C?

Use of the Global Variable in C The global variables get defined outside any function- usually at the very top of a program. After this, the variables hold their actual values throughout the lifetime of that program, and one can access them inside any function that gets defined for that program.

How do you declare a global variable inside a function in Java?

Global variables are not technically allowed in Java. A global variable is one declared at the start of the code and is accessible to all parts of the program. Since Java is object-oriented, everything is part of a class. ... A static variable can be declared, which can be available to all instances of a class.

Can you declare a global variable inside a function Python?

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.


1 Answers

You have two problems:

  1. main is not a loop. It's a function.

  2. Your function syntax is wrong. You need to have parentheses after the function name. Either of these are valid syntaxes for main:

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

Then, you can declare a local variable inside main like so:

int main() {
  int local_variable = 0;
}

or assign to a global variable like so:

int global_variable;

int main() {
  global_variable = 0;
}
like image 138
Joseph Mansfield Avatar answered Sep 28 '22 09:09

Joseph Mansfield