Compiler error: “initializer element is not a compile-time constant”

When you define a variable outside the scope of a function, that variable’s value is actually written into your executable file. This means you can only use a constant value. Since you don’t know everything about the runtime environment at compile time (which classes are available, what is their structure, etc.), you cannot create objective … Read more

Why do I get a “referenced before assignment” error when assigning to a global variable in a function?

I think you are using ‘global’ incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar. See this example: Because doA() does not modify the global total the output is 1 not 11.

Don’t understand why UnboundLocalError occurs (closure) [duplicate]

Python doesn’t have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line implicitly makes counter local to increment(). Trying to execute this line, though, will try to read the value of … Read more

Use of “global” keyword in Python

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution. The above will give you: While if you use the global statement, the variable will become available “outside” the scope of the function, effectively becoming a global variable. So the above code will … Read more

Why do I get a “referenced before assignment” error when assigning to a global variable in a function?

I think you are using ‘global’ incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar. See this example: Because doA() does not modify the global total the output is 1 not 11.

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword. E.g. This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable. The order of function definition listings doesn’t matter (assuming they don’t … Read more

How do I use extern to share variables between source files?

Using extern is only of relevance when the program you’re building consists of multiple source files linked together, where some of the variables defined, for example, in source file file1.c need to be referenced in other source files, such as file2.c. It is important to understand the difference between defining a variable and declaring a variable: A variable is declared when the compiler is informed that a … Read more