why does the name of local variables start with an underscore discouraged?

1 minute ago 1
Nature

The name of local variables starting with an underscore is discouraged mainly because in many programming languages, a leading underscore is a convention used to indicate private variables of a class, not local variables. Using this convention for local variables can cause confusion as it suggests a different meaning, typically that the variable is meant to be private or internal to a class instance. Also, in some languages such as C++, identifiers starting with an underscore followed by an uppercase letter or another underscore are reserved for implementation and can cause conflicts or undefined behavior. Specifically:

  • Underscores starting local variable names can confuse readers by implying the variable has special access or scope like private class variables.
  • In languages like Python, a leading underscore conventionally signals that the variable or method is intended for internal use (e.g., "private"), so using it for local variables breaks this expectation.
  • In C++ and some other languages, identifiers that start with an underscore followed by a capital letter or another underscore are reserved by the compiler or standard library, so their usage can lead to clashes or unpredictable results.
  • Using a single underscore as a variable name is allowed but discouraged as it can be considered unclear or confusing.

Thus, the discouragement arises due to convention and the risk of code clarity issues or unintended conflicts with reserved or special names.