Testing - acheving condition coverage with nested if's? - unit-testing

I am trying to find out if it's possible to have a set of test inputs that achieves 100% condition coverage for the following code.
bool a = ...;
bool b = ...;
if (a == True){
if (b == True && a == False){
...
} else{
...
}
} else{
...
}
However, most of the resources I have found only deal with one condition. Therefore I am not sure what to do with nested ifs. Specifically, I am not sure what to do with the second if statement. Since "a == False" should never be true given the outer if statement, is it correct to say that this code can never have 100% condition coverage test cases?

No, it's not possible: (b == True && a == False) will never be true, since it's inside a block
if (a == True)
a can't be true and false at the same time. Either there is a bug, or you have dead code that should simply be removed. And then, you can have 100% coverage.

Related

Is it good practice if container's size is validated and accessing an element under same conditional statement?

Which one of the following code is more preferable between two of them and why?
1.
std::stack<int>stk;
//Do something
if( stk.empty() == true || stk.top() < 10 )
{
//Do something.
}
or
2
std::stack<int>stk;
//Do something
if( stk.empty() == true )
{
//Do something.
}
else if( stk.top() < 10 )
{
//Do something.
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first). So, expression stk.empty() || stk.top() < 10 is safe and good practice, stk.top() is only called if stk.empty() evaluates to false. In other words, the operators were designed to enable such usage.
It entirely depends on the use case. In the first code, you have an OR condition for empty stack and checking the value of element if an element exist. So, it's clear and you can proceed with the code.
In the 2nd code, you want to execute something different for both the conditions. Hence you have put the conditions in a if else loop.
Good practise comes into sense when you don't want your code to break or pass corner test cases.You might not wan't something in your code when the stack is empty.
std::stack<int>stk;
if(stk.top() < 10 )
{
//Do something.
}
else if(stk.empty() == true)
{
//Do something
}
This will generate run time error since the stack is empty but you are accessing top element before checking the stack empty condition.
Snap of the error
I hope the answer makes it clear.

what is the use of if else statements?

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");
}

Optimized code for two string compare in if condition

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.

C++ boolean logic error possibly caused by if statements

Here is an extremely simplified version of a section of code that I am having trouble with.
int i = 0;
int count = 0;
int time = 50;
int steps = 1000;
double Tol = 0.1;
bool crossRes = false;
bool doNext = true;
for (int i=0; i<steps; i++) {
//a lot of operations are done here, I will leave out the details, the only
//important things are that "dif" is calculated each time and doNext either
//stays true or is switched to false
if (doNext = true) {
if (dif <= Tol) count++;
if (count >= time) {
i = steps+1;
crossRes = true;
}
}
}
if (crossRes = true) {
printf("Nothing in this loop should happen if dif is always > Tol
because count should never increment in that case, right?");
}
My issue is that every time it gets done with the for loop, it executes the statements inside the "if (crossRes = true)" brackets even if count is never incremented.
You've made a common (and quite frustrating) mistake:
if (crossRes = true) {
This line assigns crossRes to true and returns true. You're looking to compare crossRes with true, which means you need another equals sign:
if (crossRes == true) {
Or more concisely:
if (crossRes) {
I stand corrected:
if (crossRes)
You wouldn't have this problem if your condition was
if (true = crossRes)
because it wouldn't compile.
`crossRes = true` always evaluates to `true` because it's an assignment, to `true`.
You want `crossRes == true`:
if (crossRes == true) {
printf("Nothing in this loop should happen if dif is always > Tol
because count should never increment in that case, right?");
}
= is assignment, == is equality comparison. You want:
if (crossRes == true) {
You make the same mistake here:
if (doNext = true) { // Bad code
The other answers here have told you the problem. Often your compiler will warn you but a way to ensure that you do not do this is to put the constant term on the left
true == crossRes
that way you get a compiler error instead of a warning and so it can't escape unnoticed since
true = crossRes
wont compile.
First, although a number of people have pointed to the problem with if (crossRes = true), for some reason they haven't (yet, anyway) pointed to the same problem with if (doNext = true).
I'll stick to pointing out that you really want if (crossRes) rather than if (crossRes == true) (or even if (true == crossRes)).
The first reason is that it avoids running into the same problem from a simple typo.
The second is that the result of the comparison is a bool -- so if if (crossRes==true) is necessary, you probably need if (((((crossRes == true) == true) == true) == true) just to be sure (maybe a few more -- you never know). This would, of course, be utterly silly -- you're starting with a bool, so you don't need a comparison to get a bool.
I'd also note for the record, that if you insist on doing a comparison at all, you should almost always use if (x != false) rather than if (x == true). Though it doesn't really apply in C++, in old C that doesn't have an actual Boolean type, any integer type can be used -- but in this case, a comparison to true can give incorrect results. At least normally, false will be 0 and true will be 1 -- but when tested, any non-zero value will count as equivalent to true. For example:
int x = 10;
if (x) // taken
if (x == true) // not taken, but should be.
If you're not starting with a Boolean value as you are here, then the if (<constant> <comparison> <variable>) makes sense and is (IMO) preferred. But when you're starting with a Boolean value anyway, just use it; don't do a comparison to produce another of the same.

Why use if-else if in C++?

Why would you use if-else statements if you can make another if statement?
Example with multiple ifs:
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()
Example with else-if:
input = getInputFromUser()
if input is "Hello"
greet()
else if input is "Bye"
sayGoodbye()
else if input is "Hey"
sayHi()
If you have non-exclusive conditions:
if(a < 100)
{...}
else if (a < 200)
{...}
else if (a < 300)
....
this is very different from the same code without the "else"s...
It's also more performant.
In your first example, every if will be checked, even if input is "Hello". So you have all three checks.
In your second example, execution will stop once it found a branch, so if the user types "Hello" it will be only one check instead of three.
The difference may not be much in your simple example, but imagine that you're executing a potentially expensive function and you might see the difference.
you mean like this:
if (a == true && b == false && c == 1 && d == 0) {
// run if true
}
if (a == false || b == true || c != 1 || d != 0) {
// else
}
An else-statement would be much clearer and easier to maintain.
If you need to chose exactly one action from given set of actions, depending on some conditions, the natural and most clear choice is either switch (don't forget to break after each branch) or combination of if and else. When I write
if (conditon1)
{
action1();
}
else if (condition2)
{
action2();
}
else if (conditon3)
{
action3();
}
.
.
.
else {
action_n();
}
it is clear to the reader that exactly one of actions is to be performed. And there is no possibility that because of mistake in conditions more than one action is performed.
Following your same example if we use sequence of if conditions, whatever the input is it will run all 3 conditions. Replacing sequence of if with if-else conditions will run only first condition in best case whereas all 3 in worst case.
So conclude with that if-else will save our running time in most cases, therefore using if-else is preferred over using sequence of if conditions.
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()