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
andy
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
totemp
so that we don't lose the original value ofx
.Swap values: We assign the value of
y
tox
, effectively swapping the values ofx
andy
. Nowx
holds the value ofy
andtemp
holds the original value ofx
.Assign temporary value: We assign the value of
temp
toy
, so thaty
now holds the original value ofx
.Print the values: We use
std::cout
to print the values ofx
andy
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.