Ok, lets take the syntax error:
1 2 3 4
|
int C = A; // declaration of an integer variable with name 'C'
// The variable C is initialized with the value of variable A
A = B; // The variable A has now same value as variable B
B = int C; // syntax error
|
What does the
int
do there? Nothing sensible.
C is already a variable that has a value. The
int C
looks like a declaration of a new variable. However, that would:
1. Mask the existing C that holds a copy of A.
2. Is a syntax error.
How to do it more correctly:
1 2 3
|
int C = A; // store value of A
A = B; // move B to A
B = C; // restore original value of A to B
|
I bet that someone did not pay attention to detail.
What was the difference between
with and without braces?
Nothing. They are identical. In both cases the loop executes only one statement, the
int tmp = array[x];
Only after the loop has ended, the
std::cout << "Hello\n";
(and all the other following statements will execute.
If you want to execute more than one statement on each iteration, then you have to put all those statements within the block. Like this:
1 2 3 4 5 6
|
for (i = 0; i < x/2; ++i)
{
int tmp = array[x];
array[x] = array[y];
array[y] = tmp;
}
|
Do you feel lucky now?
Don't.
Lets look your code again:
1 2 3 4 5 6 7 8 9 10
|
int array[] = {10, 20, 30, 40, 50, 60};
int x = sizeof(array) / sizeof (array[0]); // x == 6
int y; // undefined value
int i;
for (i = 0; i < x/2; ++i)
{
int tmp = array[x]; // error: there is no array[6]
array[x] = array[y]; // error: there probably is no array[something]
array[y] = tmp;
}
|
Those are invalid memory accesses. Repeated.
What you should do there is:
use a loop to exchange the outermost pair of element values, then the next interior pair, and so on until the innermost pair of values is exchanged. |