Constants and Variables

Constants and Variables

Understanding Constants

  • Constants are values in a program that stay the same throughout its execution.
  • Named constants, i.e., giving a name to a constant value, can make programs more understandable.
  • For example, instead of using the number 3.14 each time you need pi, you could declare pi as a constant and use it wherever required.

Understanding Variables

  • Variables are values that can change during program execution.
  • They have a named reference, a type, and store a value.
  • A variable’s type determines the kind of values it can hold, such as integer, string, boolean, etc.
  • Variable names should be meaningful to reflect their purpose in the program.
  • The process of assigning a value to a variable is called variable assignment.

Using Constants and Variables

  • Constants and variables are declared before they are used in a program.
  • The scope of a variable or a constant refers to the part of the program where it can be accessed.
  • Global variables can be accessed by any part of the program, while local variables can only be accessed within the function or subroutine where they were declared.

Importance of Constants and Variables

  • Utilising constants and variables can make programs more versatile, readable, and maintainable.
  • Constants prevent hard-coding of values, improving the flexibility of the code, and making it easier to modify in the future.
  • Variables allow a program to handle different inputs and produce different outputs, making the program dynamic.

Good Practices

  • Avoid using global variables as they can make the program hard to debug and maintain.
  • Use meaningful and descriptive names for both constants and variables.
  • When working with constants, declare them at the start of the program.
  • A variable should be initialised with a value before it is used.