Using of arithmetic and logical operators in switch statement [duplicate] - c++

This question already has answers here:
Switch with range of values
(3 answers)
Closed 9 years ago.
I want to use logical operators in switch statment.
For Example:
" x is greater than 3 and is less than 7 "
Using it in If statement.
if(x > 3 && x < 7)
{
//something
}else if(x 11 3 && x < 15){
// anything
}
How can I use it in switch statement.
And how to use arithmetic operators.
UPDATE
Now how we use it in switch. Can there is not way to use it in switch.

You mean, something like this?
switch (some_var)
{ case 4 : // fall through
case 5 : // fall through
case 6 : do_something();
break;
default : do_something_else();
break;
}
It's ugly, and gets worse the larger a range you want to cover, but since switch cases must be constants, that's one way to do it.
Another way would be:
switch ((some_var > 3) && (some_var < 7))
{ case 0: do_something_else(); break;
default: do_something(); break;
}
But that'll only work if you have exactly one range you want to test. There are other ways if you have a set of equally-sized intervals that are spaced equally far apart, using some basic arithmetic, but we'd have to know a bit more about the specific problem(s) you're trying to solve...
Frankly, though, I think the if construct is the better solution...

Related

If statement for multiple values of same variable

I want to apply if statement to check a condition with multiple values, which I know should be something like this:
if (value == 1 || value == 2 || value == 3 || value == 4)
//Do something;
But this does not look good, isn't there any way to check like:
if(value == 1 || 2 || 3 || 4)
Note: I am not trying something in range like:
if (1 <= value && value <= 4)
No you can not write it as :
if(value==1 || 2 || 3 || 4)
You can use conditional statement for different conditions.
A possible simple alternative would be:
switch (value) { case 1: case 2: case 3: case 4: std::cout << "true"; }
Live sample
Wether it looks better or not is a matter of taste.
Another alternative would be:
switch (value) { case 1 ... 4: std::cout << "true"; }
Live sample
But this is not standard C++, I believe it's a GNU extension.
In case the range of possible values is smaller than the number of bits you can do something like this:
int value = 2;
auto values = {1,2,3,4};
int test = 0;
for(auto i : values)
test |= (1 << i);
if((1 << value) & test)
std::cout << "true" << std::endl;
If you have direct control over the possible values you can also directly set them as bitflags and skip the bitshift part.
Otherwise there is also the option of inverting the condition in case there are fewer possible values that should evaluate to false.
Also you could just loop over an array of valid values and see if any of them matches.
No you cannot write the way you have described. You still have option of switch case and ternary operators.
If you want to make it fancy you still have option like
vector<int> v = {1,2,3,4,5}; // desirable values
auto it = find(v.begin(), v.end(), value);
if(it != v.end()){
cout<<"value is equal to something!\n";
// if you want to check which value does it match to
cout<<"Matching value is at index "<<it-v.begin()<<"\n";
}else {
cout<<"Value is not equal to any number!\n";
}
For this you will need to include vector library by using #include <vector>
Well, I had the same issue and this is the solution I came up.
I created an array, with the values I want to check, and then I use the native array includes() method to check if the variable value exists on the array. Like this:
[1, 2, 3, 4].includes(value);
If the variable value exists on the array the includes() method will return a boolean with the value true. Otherwise it will return a boolean with the value false.

Rewriting an if statement to make it more condensed and cleaner [duplicate]

This question already has answers here:
Concise way to say equal to set of values in C++
(5 answers)
Closed 6 years ago.
I am working on a school assignment. What I want to do is not the focus of the assignment, merely something I would like to do better.
I have the following if statement where equation is a string
if( (equation[0]== "*") || (equation[0]== "/") || (equation[0]== "+") || (equation[0]== "-"))
All it does is check to see if the first and last characters of the string are one of 4 operators. This is long, bulky, and hopefully not the best way of doing this. Sadly I do not have access to regular expressions as this type of check would be very easy using them.
Is there a better way of writing the if statement without using regular expressions? Something along the lines of
if( equation[0] == ("/" || "*" || "+" || "-"))
How about
if(std::string("*/+-").find(equation[0])!=std::string::npos)
You may consider using switch operator
switch(equation[0]) {
case '/':
case '*':
case '+':
case '-':
//your code
break;
default:
//else statement
}
I don't think it is possible to do what you're asking.
Best you can do is put equation[0] in another shorter name variable.
std::string a = equation[0];
if( (a"*") || (a== "/") || (a== "+") || (a== "-"))
No, that's not possible. But I think it's always cleaner and more readable to
switch (equation[0]) {
case '*':
case '/':
case '+':
case '-':
//dostuff
break;
default:
//dostuff
}
This way, it's also really easy to replace (add or remove) new characters. If you would to it with a regular expression, that would be definetely more work to do.

How does switch statement compares values? [duplicate]

This question already has answers here:
Does case-switch work like this?
(5 answers)
Closed 8 years ago.
Given the following sequence
switch(1) {
case 1:
cout << "first \n";
case 2:
cout << "second \n";
default:
cout << "Not first nor the second";
}
the output is
first
second
Not first nor the second
I'm expecting the output to be
first
so, how do values are compared? I know I didn't use the break statement, but isn't that just to save cpu time? How come the second case executes since there are two different integer values? What am I missing?
I'm using gcc 4.9.2 with -std=c++11 flag.
If you don't use break the code just continues. I guess it's a bit like a GOTO label in that sense. There are legitimate uses for omitting the break statement, such as when you want to do an or ...
switch(val) {
case 1:
case 2:
// if val is 1 or 2...
break;
case 3:
// if val == 3;
break;
}

how to compare string to multiple char c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to find out whether a string has words in it
if( mystring[i] == 'a' | 'b' | 'c' | 'd' | 'e' |)
// do stuff but it always does stuff no matter that mystring[i] is.
is always evaluating to true even if mystring[i] = a space or a period
I tried to use strcmp but I couldn't get that working right. I want it to evaluate true
only if it = a letter.
You cannot compare multiple values like that. Use a switch statement instead:
switch( mystring[i] )
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
{
// do something
break;
}
default:
{
// do something else
break;
}
}
In C/C++, if a case block does not have a break then its execution will continue in the next case block. Thus, all 5 values will execute the same // do something code. Some languages do not do that.
Another option, only because your values are consecutive, is to use this:
char ch = mystring[i];
if( (ch >= 'a') && (ch <= 'e') )
{
// do something
}
else
{
// do something else
}
There are two issues in your code. First, due to precedence, your expression is being evaluated as:
(mystring[i] == 'a') | ('b') | ('c') | ('d') | ('e')
Second you are using bitwise-or instead of logical-or. What you want to do is have a full condition as each term and switch to logical or:
char c = mystring[i];
if (c == 'a' || c == 'b' || c == 'c' ...)
Finally, if you are planning to check for every lower case letter, the standard library has an islower method which can check that:
if (islower(mystring[i])

Statements in C++

In C++ want to write something like this
int Answer;
if (Answer == 1 || Answer == 8 || Answer == 10)
and so on, is it any way to make code shorter without repeating variable always?
Try:
switch (Answer) {
case 1: // fall through
case 8: // fall through
case 10:
// ... do something
break; // Only need if there are other case statements.
// Leaving to help in mainenance.
}
For readability I'd encapsulate the logic in descriptively-named functions. If, say, your answers are things with a particular color, and answers 1, 8, and 10 are green things, then you can write that logic as
bool ChoiceIsGreen(int answer)
{
return (answer == 1 || answer == 8 || answer == 10);
}
Then your function becomes
if (ChoiceIsGreen(Answer))
{
// offer some soylent green
}
If you have a lot of choices like this, I can see it getting hard to read if you have a lot of raw numbers all over the place.
If and only if you need to optimise for code size manually, and Answer is guaranteed to be positive and less than the number of bits in an int, you might use something like
if ( ( 1 << Answer ) & 0x502 )
But normally you don't want to obscure your logic like that.
You could put the values into a container and search the container.
Sounds like a std::set would be a wise choice:
if answer is in the set of (1, 8, 10) then do....
Remember that a std::set must be initialized during run-time, unlike numeric constants or an array of numeric constants. Before making any performance changes, first get the program working correctly, then profile if necessary, that is only if the program demands performance optimization.