temporary variable ex c++

Sure! Here is an example of using a temporary variable in C++:

#include <iostream>

int main() {
   int x = 5;
   int y = 10;

   int temp = x;
   x = y;
   y = temp;

   std::cout << "x: " << x << std::endl;
   std::cout << "y: " << y << std::endl;

   return 0;
}
  • Declare variables: In this example, we declare two integer variables x and y and initialize them with the values 5 and 10 respectively.

  • Declare a temporary variable: We declare another integer variable temp to store the temporary value.

  • Assign values: We assign the value of x to temp so that we don't lose the original value of x.

  • Swap values: We assign the value of y to x, effectively swapping the values of x and y. Now x holds the value of y and temp holds the original value of x.

  • Assign temporary value: We assign the value of temp to y, so that y now holds the original value of x.

  • Print the values: We use std::cout to print the values of x and y after the swap.

  • Return statement: The return 0 statement indicates that the program has executed successfully.

This code snippet demonstrates how a temporary variable can be used to swap the values of two variables.