Understanding Variables in C++

  • Last updated Apr 25, 2024

In C++, variables are used to store and manipulate data. Variables are defined with a specific data type, which determines the kind of data they can hold.

Some key points about variables in C++:

  1. Variable Declaration:
  2. A variable can be declared by specifying its data type and name. For example:

    int age; // Declaring an integer variable named 'age'
    double pi; // Declaring a double-precision floating-point variable named 'pi'
    char initial; // Declaring a character variable named 'initial'
  3. Variable Initialization:
  4. You can optionally initialize a variable at the time of declaration, which assigns an initial value to it. For example:

    int count = 20; // Initializing an integer variable with the value 20
    double temperature = 32.4; // Initializing a double variable with a floating-point value
    char grade = 'A'; // Initializing a character variable with the character 'A'
  5. Variable Assignment:
  6. After declaration, you can assign values to a variable using the assignment operator =. For example:

    age = 32; // Assigning the value 32 to the 'age' variable
    pi = 3.141592; // Assigning a new value to the 'pi' variable
    initial = 'B'; // Reassigning the 'initial' variable with the character 'B'
  7. Variable Scope:
  8. Variables have scope, which defines where in the code they can be accessed. Variables declared within a block (such as a function or a pair of curly braces) are local to that block, while those declared outside of all functions have global scope. Function parameters are also local variables.

    int globalVar = 70; // Global variable
    
    void someFunction() {
        int localVar = 8; // Local variable within the function
        
    }

    A variable can be declared using the static, auto, or extern keyword.

    • static:
    • When a variable is static, the space in memory for that variable is allocated only once throughout the entire program. A static variable exists till the end of the program once it is declared in the program. For example:

      #include <iostream>
      
      // Global static variable with file scope
      static int globalStaticVar = 100;
      
      void function() {
          // Local static variable inside the function
          static int localStaticVar = 0;
      
          // Increment and print the local static variable
          localStaticVar++;
          std::cout << "Local Static Variable: " << localStaticVar << std::endl;
      }
      
      int main() {
          // Access and print the global static variable
          std::cout << "Global Static Variable: " << globalStaticVar << std::endl;
      
          // Call the function multiple times to increment and display the local static variable
          function();
          function();
          function();
      
          return 0;
      }

      In this example, globalStaticVar is a global static variable declared at file scope, and it has internal linkage. This means it is accessible from within the entire translation unit (source file). On the other hand, localStaticVar is a local static variable declared inside the function, and it retains its value between calls to the function; it is initialized only once.

    • auto:
    • When a variable is declared using the auto keyword, the C++ compiler automatically detects and assigns the data type to that variable based on the value assigned to it. All the variables inside the function are default considered as an automatic variable. For example:

      #include <iostream>
      
      int main() {
          auto number = 40; // 'auto' deduces the type as int
          auto name = "John"; // 'auto' deduces the type as const char*
          auto pi = 3.141592; // 'auto' deduces the type as double
      
          // Display the values and data types of the variables
          std::cout << "number: " << number << " (Type: " << typeid(number).name() << ")" << std::endl;
          std::cout << "name: " << name << " (Type: " << typeid(name).name() << ")" << std::endl;
          std::cout << "pi: " << pi << " (Type: " << typeid(pi).name() << ")" << std::endl;
      
          return 0;
      }
    • extern:
    • In C++, you can use the extern keyword to declare an external variable. An external variable is a variable defined in one source file and declared in another. It allows you to share the variable across multiple source files in a program.

      Here's an example of how to use extern with a variable:

      Let's say you have two source files, main.cpp and external.cpp, and you want to share a variable between them:

      main.cpp:

      #include <iostream>
      
      // Declare the external variable from external.cpp
      extern int sharedVariable;
      
      int main() {
          std::cout << "Main.cpp: sharedVariable = " << sharedVariable << std::endl;
          sharedVariable = 90; // Modify the shared variable
          std::cout << "Main.cpp: sharedVariable = " << sharedVariable << std::endl;
      
          return 0;
      }

      external.cpp:

      // Define the shared variable in external.cpp
      int sharedVariable = 70;

      In this example, in external.cpp, we define an integer variable named sharedVariable and give it an initial value of 70. In main.cpp, we declare the sharedVariable as an external variable using extern. This tells the compiler that the variable is defined in another source file. We can then use the sharedVariable in main.cpp as if it were defined there. We first print its initial value, and then we modify it to 90.

  9. Constants Variables:
  10. Constant variables are variables whose values cannot be changed after initialization. They are declared using the const keyword. For example:

    const int constantValue = 10; // A constant integer variable
  11. Naming Conventions:
  12. Variable names in C++ must start with a letter or an underscore and can contain letters, digits, and underscores. Variable names are case-sensitive. For example:

    int myVariable; // Valid variable name
    double MyVariable; // Different from the previous variable due to case sensitivity
    int my_variable; // Underscores are allowed