Answer the question
In order to leave comments, you need to log in
How to beautifully implement multiple conditions in C++?
There is a moment in the code that has many conditions.
if (water[qX][qY] < water[x][y] && qX >= 0 && qY >= 0 && qX < room_size && qY < room_size && water[x][y] != 0) {...}
if (qX >= 0 && qY >= 0 && qX < room_size && qY < room_size)
if (water[qX][qY] < water[x][y] && water[x][y] != 0) {
...
}
if (qX >= 0 && qY >= 0)
if (qX < room_size && qY < room_size)
if (water[qX][qY] < water[x][y] && water[x][y] != 0) {
...
}
Answer the question
In order to leave comments, you need to log in
Complex conditions should be broken down into simple ones. as well as complex functions should be broken down into simple ones.
This condition, as I see it, checks for the occurrence of a rectangle? Best in a separate function. Will increase readability.
for example like this:
bool isInRoom(int qX, int qY, int room_size)
{
if (qX < 0)
return false;
if (qY < 0)
return false;
if (qX >= room_size)
return false;
if (qY >= room_size)
return false;
return true;
}
if (isInRoom(qX, qY, room_size) && water[qX][qY] < water[x][y] && water[x][y] != 0)
...
if (! isInRoom(qX, qY, room_size)) // проверка предусловия
return;
if (water[qX][qY] < water[x][y] && water[x][y] != 0)
...
In nested conditions, it makes sense when the algorithm branches, that is, there is a bunch of else.
In general, it's good to stick to standards. If you work in a company, ask how they usually act at such moments. If you write on your own, do as you see fit. Just stick to one style.
For example, try making the condition multi-line. Something like:
if (
water[qX][qY] < water[x][y]
&&
qX >= 0
&&
qY >= 0
&&
qX < room_size
&&
qY < room_size
&&
water[x][y] != 0
) {...}
Modern compilers do not care how to arrange the conditions - in one if or in several. Don't believe? Try to tell the compiler the switches that generate the assembler code and see that there is no difference.
gcc -S yousource.c - will generate an assembler file using the gcc compiler
cl.exe /FAs /c yousource.c - will generate an assembler file using the Microsoft Visual C command line compiler
Line 133 pastebin.com/tdiqwpSf
Here I made a part of the check into a separate function... of course, it doesn't seem very nice to me...
I want the entire block from line 133 to 156 into a separate function. But links, links, and so on will only confuse me more, it seems to me.
I would write like this:
if (water[qX][qY] < water[x][y] &&
qX >= 0 && qY >= 0 &&
qX < room_size && qY < room_size &&
water[x][y] != 0) {
...
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question