Global variables
-
How to set a variable global
-
all variables are global by default, except the ones in functions
-
@Hector1945 And if I want to use them in functions?
-
If you have declared the variable outside of the function, before using it in the function, it is global.
For example:
int myVariable = 0; // This variable is now declared in the global scope (and I assigned the value 0) function setMyVariable(value) myVariable = value // assign a new value to myVariable return value print(myVariable, "\n") // prints 0 int returnValue = setMyVariable(1) print(returnValue, "\n") // prints 1 print(myVariable, "\n") // prints 1
if you want to make sure the variable is scoped to the function only, you need to declare it in the function:
int myVariable = 0; // This variable is now declared in the global scope (and I assigned the value 0) function setMyVariable(value) int myVariable = value // by beginning with the type, I'm declaring a new variable at the scope of the function (and I assign value to it) return myVariable print(myVariable, "\n") // prints 0 int returnValue = setMyVariable(1) print(returnValue, "\n") // prints 1 print(myVariable, "\n") // still prints 0
-
@PB____ Thanks
-
Is this pseudo code ?
-
No, not really, but I did accidentally used a
;
on the first line. If you remove that, it should work. -
@PB____ C++ left the chat