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
}
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.
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.
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.
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.
You have two problems:
main
is not a loop. It's a function.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With