Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using elses in boolean functions c++

Tags:

c++

Let's say I have a simple function that checks a condition and returns true if the condition is true and false if the condition is false.

Is it better to use this type of code:

bool myfunction( /*parameters*/ ) {
    if ( /*conditional statement*/ ) {
        return true;
    }
    return false;
}

Or this type:

bool myfunction( /*parameters*/ ) {
    if ( /*conditional statement*/ ) {
        return true;
    }
    else return false;
}

Or does it just really not make a difference? Also, what considerations should I bear in mind when deciding whether to "if...else if" vs. "if...else" vs. "switch"?

like image 772
Adam Gluntz Avatar asked Jun 01 '26 20:06

Adam Gluntz


2 Answers

You can also write this without any conditional at all:

bool myfunction( /*parameters*/ ) {
    return /*conditional statement*/;
 }

This way you avoid the conditional entirely.

Of course, if you are dealing with a different function where you need the conditional, it shouldn't make a difference. Modern compilers work well either way.

As far as using switch vs if-else, switch adds efficiency when you have many cases by allowing you to jump to a single one, making execution faster by not running all cases. At a low (hardware/compiler level), switch statements allow you to make a single check/jump, where if you had many if statements, you would need to make many checks/jumps.

like image 83
fileyfood500 Avatar answered Jun 03 '26 08:06

fileyfood500


It is the same. Remember whenever you say

return boolean;

the function ends and return to its calling line. Therefore putting it inside else or just simply putting it is same.

say we want to check the prime

bool isPrime (int n){
     for (int i = 2; i <= sqrt(n); i++){
         if (n % i == 0)
             return false;
     }
     return true;
}

if you see the function closely you will know if the number is divided properly with any value in range of sqrt(n) it will return false as the number is not a prime.. if it cannot be divided then the loop will end without any interference and said the number to be a prime. hence forth the function works properly.

like image 43
exilour Avatar answered Jun 03 '26 09:06

exilour