I'm doing a problem I found on this website for practice to understand Local variables, scopes & duration.
Write a program that asks the user to enter two integers, the second larger than the first. If the user entered a smaller integer for the second integer, use a block and a temporary variable to swap the smaller and larger values. Then print the value of the smaller and larger variables. Add comments to your code indicating where each variable dies.
#include <iostream>
usingnamespace std;
int main()
{
int smaller;
int larger;
cout << "Enter two integers." << endl;
cin >> smaller >> larger;
if(smaller > larger){
// I do not understand the following below inside the block
// Can someone please explain I want to learn.
int temp = larger;
larger=smaller;
smaller=temp;
} // temp dies here
cout << "The smaller integer is" << smaller << endl;
cout << "The larger integer is " << larger<< endl;
return 0;
}
Your question seems to be all about scope. What parts of you program can use what variables.
smaller and larger are defined so every part of main() can use them. The if block defines temp and is only usable in the block, in this case defined by the curly braces.
When you use that opening curly brace (line 12) you enter a higher level of scope. This means you can access the variables from lower levels of scope and you can create variable that are localised to this level of scope and above. Because you declare temp inside the block of the if, that is its scope level and when that scope level ends (line 24), any variables which are localised to that scope are destroyed. Hence, you would not be able to access temp after line 24. Temp is used because if you didn't, you'd lose the value of either smaller or larger when you assigned them the other's value.
This block of code creates a local integer named temp to:
1. Hold the value of larger, then
2. Assign the value of smaller to larger, then
3. Assign the value of temp (what larger was) to smaller.