-
just wondering
ok i have the book teach yourself C++ in 21 days and one of the sections is this
Blocks and Compound Statements
Any place you can put a single statement, you can put a compound statement, also called a block. A block begins with an opening brace ({) and ends with a closing brace (}). Although every statement in the block must end with a semicolon, the block itself does not end with a semicolon. For example
{
temp = a;
a = b;
b = temp;
}
This block of code acts as one statement and swaps the values in the variables a and b.
and i was wondering what you would need that for? it seems like its just a circle.
-
This could be used for sorting, for example
axon
-
"and i was wondering what you would need that for?"
The code in your example switches the values in a and b. Let's say you started out with:
a=5
b=10
and you wanted to switch the values. If you tried this:
a=b;
b=a;
the first statement would assign 10 to a, so you would have:
a=10
b=10
The second statement assigns a to b, and since a=10, you assign 10 to b, so you have:
a=10
b=10
So, in the end were you able to switch the values? No, you wanted to end up with:
a=10
b=5
To switch values in two variables, you have to create a temp variable because your first assignment is going to overwrite the value in that variable and it will be lost forever unless you assign the value to temp first.
temp = a; ----->temp=5, a=5, b=10
a=b; ---------->temp=5, a=10, b=10
b=temp-------->temp=5, a=10, b=5
-
sreetvert83, ignore this post. I'm just trying to confuse others:D
This code:
a=b;
b=a;
will work in a certain case. What's this case? (Hint: the variables don't have to be the same value)