Can someone explain this syntax of using for and if side by side?
int min_dist = huge;
int v = -1;
for (int i = 0; i < N; ++i) if (!done[i]) {
if (d[i] >= min_dist) continue;
min_dist = d[i];
v = i;
}
It's not side by side. It's an if inside a for. The syntax of a for is
for(...)
statement
And it just so happens that an if is also a statement. So your code is equivalent to this:
for(...)
if() {
}
Because white-spaces are pretty much ignored by the compilation process. It doesn't matter if there's a new line or not. It's still a statement. Just like it doesn't matter for the one-liner
if (d[i] >= min_dist) continue;
And if we don't omit those obviously crucial braces:
for(...) {
if() {
}
}
We'll be far less likely to be confused in the future.
for(...) if (...) on one line.This is a case of poorly indented and organized code. It is equivalent to:
for (int i = 0; i < N; ++i)
{
if (!done[i])
{
if (d[i] >= min_dist) continue;
min_dist = d[i];
v = i;
}
}
Adding the block {} right after the for line makes it easier to read.
You can add another block for the second if statement to make it still easier.
for (int i = 0; i < N; ++i)
{
if (!done[i])
{
if (d[i] >= min_dist)
{
continue;
}
min_dist = d[i];
v = i;
}
}
You can simplify it to:
for (int i = 0; i < N; ++i)
{
if (!done[i])
{
if (d[i] < min_dist)
{
min_dist = d[i];
v = i;
}
}
}
The two ifs can be combined to make it simpler still.
for (int i = 0; i < N; ++i)
{
if (!done[i] && d[i] < min_dist)
{
min_dist = d[i];
v = i;
}
}
This is exactly the same:
int min_dist = huge;
int v = -1;
for (int i = 0; i < N; ++i){
if (!done[i]) {
if (d[i] >= min_dist) continue;
min_dist = d[i];
v = i;
}
}
As an explanation, when you only have one statement inside a for or if, you don't need the brackets.
I always find when looking at code I don't understand the best method is to rewrite it in a format which I find easier to read, in this case:
for (int i = 0; i < N; ++i) {
if (!done[i]) {
if (d[i] >= min_dist) {
continue;
}
min_dist = d[i];
v = i;
}
}
The fact that the if statement is beside the loop merely means that that is the expression to be resolved as the loop body (note this is always the case, blocks {} are also used). This if then has a body as well, by putting in the omitted blocks explicitly it is easier to see what is going on.
The right way to write this code is like this:
for (int i 0; i < N; ++i)
if (!done[i] && d[i] < min_dist) {
min_dist = d[i];
v = i;
}
Putting the if on the same line as the for just confuses things. As is having two if statements instead of one.
side by side?if()statement as its body. So the programmer went clever, and omitted the braces of the loop body.