Using global variables in a function
You can use a global variable within other functions by declaring it as global
within each function that assigns a value to it:
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
Since it's unclear whether globvar = 1
is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global
keyword.
See other answers if you want to share a global variable across modules.
Creating global variables inside function - why does this work?
Afaik, variables declared inside a function are local variables (using var keyword or not).
Variables declared inside a function are local, but you are not declaring any variables. What you have is what's known as an "implicit global" and it only works in "sloppy mode".
From MDN:
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.
In strict mode, your code produces an error:
"use strict";
function func1() { x = 5;}
function func2() { document.write(x);}
func1();func2();
Declaring a global variable inside a function
you have to define the global var in the second function as well..
// global scope
$ref_id = 1;
grabReferral($rid){
global $ref_id;
$ref_id = $rid;
}
someOtherFunction(){
global $ref_id;
sendValue($ref_id);
}
felix
How to declare a Global variable inside any function in 'C'?
You may want to use an array allocated into the heap by using malloc
#include<stdio.h>
int *a;
int main()
{
int n;
scanf("%d", &n);
a = malloc(sizeof(*a) * n);
if(a == NULL) {
// malloc error
}
// use your array here
free(a); // at the end of the program make sure to release the memory allocated before
}
How to declare global variable inside 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;
}
initialize global variable in method
If you want to make some variable global then you would need to declare the variable outside the method. In java, you cannot declare static variables inside method (even if it is static) because inside method all variables are local variables that has no existence outside this method thats why they can't be static.
import java.util.*;
public class GlobalVariable{
static int b;
public static void main(String...args){
GlobalVariable.compare(1);
System.out.println(b);
}
static void compare(int a){
Scanner sc = new Scanner(System.in);
b = sc.nextInt();
}
}
why can't I declare a global variable inside an exec string
You have to declare that you are using global ostr in the function to be able to print it. This piece of code outputs
def function():
global ostr
exec("global ostr; ostr = nstr")
#global ostr; ostr = nstr
print(ostr)
lv='ostr' in globals()
print(lv)
ostr='asd'
worked
True
Edit: Just realised the exec actually works with global variables, if you re-run your code and print(ostr) in the global main you will see it was changed.
ostr = "didn't work"
nstr = "worked"
def function():
#global ostr
exec("global ostr; ostr = nstr")
function()
print(ostr)
worked
Edit#2: Either declare ostr as a global variable before modifying it, or assign it to another local variable.
ostr = "didn't work"
nstr = "worked"
def function():
exec("global ostr; ostr = nstr")
#global ostr; ostr = nstr
print(ostr)
lv='ostr' in globals()
print(lv)
function()
worked
True
Related Topics
How to Get the Home Directory from a PHP Cli Script
Laravel 5.2: the Process Class Relies on Proc_Open, Which Is Not Available on Your PHP Installation
Codeigniter Echoing [::1] Instead of Localhost
Best Way to Delete "Column" from Multidimensional Array
Copy Large Files (Over 2 Gb) in PHP
Pretty Urls Without Mod_Rewrite, Without .Htaccess
Fatal Error: Allowed Memory Size of 268435456 Bytes Exhausted (Tried to Allocate 71 Bytes)
Change Database Connection in Laravel Model
Send Fcm Messages from Server Side to Android Device
PHP - Cannot Use a Scalar as an Array Warning
How to Execute a Shell Script in PHP
Accessing a Variable Defined in a Parent Function
Best Way to Parse an Invalid HTML in PHP
Php/Gd - Transparent Background
Accented Characters in MySQL Table