I want to do two string compare and used two different if condition. Is there any better way to do string compare in one if condition
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
}
The equivalent code is:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
Note: The compiler should generate the same machine code for both code samples. The difference is cosmetic and primarily aimed at the reader of the code.
You do get a difference when you add else clauses:
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
else
{
// else 1
}
}
else
{
// else 2
}
Compared to:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
else
{
// Single else clause
}
In addition to Klas's answer(just in case you're not familiar with the AND operator) - the AND operator ('&&') checks the first condition and it continues to check the second condition -only if- the first condition is true.
So in your specific question, it checks if the first couple of strings are equal and only if true (are equal), it checks if the second couple are also equal.
The obvious optimization (not mentioned yet), if you know anything about those strings, is to first perform the compare that is more likely to fail.
Related
I have a problem with the while loop, I have instructed that the key1 variable should only be executed when at least some "if" instructions have been executed, however, it re-executes the while loop even if the variable key1 is equal to 0.
It should be noted that I do not change the value of the key1 variable in another part of the function
void form_table(...) {
int key1=1;
while (key1 != 0) <==(2)
{
key1=0;
if (dx->get_numero() == 1 && dy->get_numero() == 1)
{
key1++;
//Some code
}
else if (dx->get_numero() == 1 && dy->get_numero() == 0)
{
key1++;
//some code
}
else if (dx->get_numero() == 0 && dy->get_numero() == 1)
{
key1++;
//some code
} <==(1)
else
break;//I put it in case, but even with that it goes back into the buble while
}
}//Here is the problem, when finish the funcion execution the program comes back to the line (1), and then re-runs the while cycle (2)
the loop works if key1 is different from 0 if you increment key1 and therefore it is different from 0 the cycle reinitiates.
you have to do:
while (key1 == 0) {
// rest of the code
}
I don't quite understand the meaning of else if statements.
why not just to continue with the if statements in case one is false?
it works the same.
example with if only that will work the same with else if:
function testSize(num) {
if (num < 5){
return "Tiny";
}
if (num < 10){
return "small";
}
return "Change Me";
}
testSize(7);
In your actual code you specify a return statement in the code associated to the if statement.
Suppose you don't specify a return statement or suppose today you specify a return statement but tomorrow you remove it to do a common return at the end of the method.
This code will test each condition even if the first one is true :
if (num < 5){
// do something
}
if (num < 10){
// do something
}
This code will not test the next condition if the first one is true :
if (num < 5){
// do something
}
else if (num < 10){
// do something
}
These two ways of doing have two distinct meanings.
When you have a series of if statements, you expect that more than one condition may be true.
When you have a series of if-else-if statements, you expect to have not more than one condition true.
Using the first form (a series of if) while functionally you expect to have not more than one condition true is misleading.
Besides, if the code is modified and you add a condition that is both true for two if statements while you don't want have this case, it would create an issue.
Your code is only showing your belief. What would happen in the example below?
function testSize(num) {
if (num < 5){
x = 1;
}
if (num < 10){
x = 2;
}
result = complex calculations;
}
function testSize2(num) {
if (num < 5){
x = 1;
} else if (num < 10){
x = 2;
}
return x * 2;
}
testSize(4); // result is 4
testSize2(4); // result is 2
x may also be involved in more calculations
if(condition) {...}
if(condition) {...}
if(condition) {...}
In above code, even if the first or second condition is true, third condition have to be checked.
if(condition) {}
else if(condition){}
else if(condition){}
Here if first condition is true, next two will not be checked. So, it saves time and is more readable logically.
A one way if statement takes an action if the specified condition is true.If the condition is false, nothing is done. But what if you want to take alternative actions when the conditions is false ? You can use a two-way if-else statement. The action that a two-way if-else statements specifies differ based on whether the condition is true or false.
Well, there is a bit different from this two statement.Consider the follow samples
if(a > 0) {
...
}
if( a == 0) {
...
}
if(a < 0) {
...
}
and
if(a > 0) {
...
}
else if( a == 0) {
...
}
else if(a < 0) {
...
}
when a is zero the last else if statement will not be execute while if need to compare third time.If a equals to 10, else if could be execute once while if is third.From this else if statement could be execute less and let your program a bit fast.
else if should be used when there are multiple conditions and you want only one of them to be executed, for instance:
if(num<3){ console.log('less than 3') }
else if(num<2){ console.log('less than 2')
If you use multiple if statements instead of using else if, it will be true for both the conditions if num = 1, and therefore it will print both the statements.
Multiple if statements are used when you want to run the code inside all those if statements whose conditions are true.
In your case it doesn't make a difference because the function will stop and return at the very first return statement it encounters. But let's say, the blocks' orders are interchanged, then your function will never return 'tiny' even if num = (anything less than 5).
I hope that helps!
If all your if branches terminate the function (e.g., but returning a value of throwing an exception), you're right, and you really don't need an else statement (although some coding standards might recommend it).
However, if the if branches don't terminate the function, you'd have to use an else or else if clause to prevent multiple blocks from being executed. Assume, e.g., you want to log a message to the console instead of returning it:
if (num < 5) {
console.log("Tiny");
} else if (num < 10) {
console.log("small");
} else {
console.log("Change Me");
}
Suppose I have:
QString x;
Is the following code fragment:
if(x.compare("abcdefg") == 0){
doSomething();
}
else{
doSomethingElse();
}
... functionally equivalent to:
if(x == "abcdefg"){
doSomething();
}
else{
doSomethingElse();
}
I could prove this for myself by writing a fairly trivial program and executing it, but I was surprised I couldn't find the question / answer here, so I thought I'd ask it for the sake of future me / others.
QString::compare will only return zero if the string passed to it and the string it is called on are equal.
Qstring::operator== returns true if the strings are equal otherwise, false.
Since compare only returns zero when the strings are equal then
(qstrign_variable.compare("text") == 0) == (qstrign_variable == "text")
If qstrign_variable contains "text" in the above example. If qstrign_variable contains something else then both cases evaluate to false.
Also note that std::string has the same behavior
I have a mini program I’m working on for class. The program is of correct syntax. Logically I cannot get the program to compute the remaining data after it completes the first else if statement that it matches.
I am subtracting numbers from each (a >= b) at each else if, the remaining value I am then assigning to a variable temp and using (temp >= c), rinse and repeat till value is zero. Each else if, will assign a char ‘A’ – ‘Z’ depending on the scenario. The problem I am having is it will meet one of the first else if’s but will not continue working the remaining else-ifs. I know this is standard of how if, else works. My question is how would I go about getting the remaining else ifs examined after the first one checks out. Is the only solution to use a switch function? Is there no way I can use if else and have each else checked/passed till my value = 0?
Just forget using else if, use a chain of if statements instead. For example:
bool isThisThree(int number, string &message)
{
if(number == 1)
message = "No, it's a one!";
if(number == 2)
message = "No, it's a two!";
if(number == 3) {
message = "Yes!";
return true;
}
if(number == 4)
message = "No, it's a four!";
if(number == 5)
message = "No, it's a five!";
return false;
}
In this example, the if statements will be examined one by one until the function hits a return statement.
A part of my program (I can add more details if necessary) contains this line:
if((e->start->explored = false) || (e->end->explored = false)){
//do action...
}
This is part of a graph algorithm, where e is a directed edge with incident vertices "start" and "end." I would like the 'action' to happen if at least one of the incident vertices of e is unexplored, but this logic appears to be faulty. Although I used a small example and verified that, indeed, the start and end vertices of my edges were unexplored to start with, my overall function is going into an infinite loop.
So then I tested it like this:
if((e->start->explored = false) || (e->end->explored = false)){
//do action...
}
else cout << "FAIL";
...and, of course, it printed a screen of "FAIL." What is my logic error here?
You're assigning false to your properties instead of testing them against false. This is a mistake often made, and quite hard to debug. Change your = assignment operator to the equality operator ==:
if((e->start->explored == false) || (e->end->explored == false)) {
// Do action...
} else {
cout << "FAIL";
}
Instead of comparing the values to false, it's clearer to use the ! not operator instead. The inner brackets are done away with, too:
if(!e->start->explored || !e->end->explored) {
// Do action...
} else {
cout << "FAIL";
}
As the others have expounded you accidentally used assignment instead of comparison. However, the real solution is not to compare at all:
Comparing bool values to literals true and false is nonsensical!
Instead, write:
if(! e->start->explored || ! e->end->explored)
You have used the assignment operator = not the comparison operator ==.
You are assigning values here:
if((e->start->explored = false) || (e->end->explored = false)){
Should be:
if((e->start->explored == false) || (e->end->explored == false)){