Is declaring variables mid processing bad practice?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bellpepper

In Computer Science classes, I’ve been taught that variables should be declared before any processes take place.
In Godot however, you will see people write code in opposition of this.
Is there any significance in actually declaring variables before or during processing?

:bust_in_silhouette: Reply From: Chlipouni

It depends on the scope of the variable.

A variable may be used only by :

  • a few lines of code (a “for loop” use a local variable with implicit declaration)
  • a function
  • a class

You can also define a global variable with the singleton (AutoLoad) technic in Godot.

As a variable consumes memory, it is better for efficiency and performance to choose the right scope for each variable.

This advice is general regardless of the programming language you use.
Today we have computers with a large memory, but when I started to learn programming, it was not.

Thanks for the answer. This is helpful to know.

bellpepper | 2020-06-07 07:28