switch expression syntax

hi!!

i want to do something like this:

1
2
3
4
5
6
7
8
9
10
int wd;
int wdd[3];
int i;
switch (wd==wdd[i])
   case 0:
     break;
   case 1:
     break;
   case 2;
     break;


is it possible??? can you suggest another solution?
closed account (o3hC5Di1)
Hi there,

The expression (wd==wdd[i]) is a boolean expression.
That means it will only return true or false.
So you cannot check beyond 0 or 1 here.

I'm not sure what you're trying to do here, but alternatively you could use if, if else, else:

1
2
3
4
5
6
7
8
if (number1 > number2)
{ ...}
else if (number1 < number2)
{ ... }
else if (number1 == (number2+3))
{ ... }
else
{ .. }


Hope that helps.

All the best,
NwN
1
2
3
4
5
if( wd == wdd[i] )
{
  switch( wd )
    case 0:.......
}


?
Just playing with ideas here, it feels like this isn't the best way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    int wd = 678;
    int wdd[3] = {012, 345, 678};

    for (int i=0; i<3; i++)
    {
        if (wd==wdd[i])
        {
            switch (i)
            {
                case 0:
                    cout << "one";
                    break;
                case 1:
                    cout << "two";
                    break;
                case 2:
                    cout << "three";
                    break;
            }
        }
    }

Output:
three


Or a variation of the above, pull variable i outside the for loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    int i;
    for (i=0; i<3; i++)
        if (wd==wdd[i])
            break;

    switch (i)
    {
        case 0:
            cout << "one";
            break;
        case 1:
            cout << "two";
            break;
        case 2:
            cout << "three";
            break;
        default:
            cout << "not found";
    }
Last edited on
Switch syntax:

1
2
3
4
5
6
7
8
9
10
switch(int_variable) {
   case 0:
      cout << "int_variable equals 0" << endl;
      break;
   case 1:
      cout << "int_variable equals 1" << endl;
      break;
   default:
      cout << "int_variable does not equal any of the above cases" << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int wd;
int wdd[3] = { /* some values */ };

switch ( std::distance( std::begin( wdd ), std::find( std::begin( wdd ), std::end( wdd ), wd ) ) )
{
case 0:
   std:;cout << "zero";
   break;
case 1:
   std::cout << "first";
   break;
case 2:
   std::cout << "second";
   break;
default:
   std::cout << "Not found";
   break;
}
Last edited on
Vlad, what header does that use?
#include <algorithm>
#include <iterator>

and of course

#include <iostream>

provided that your compiler supports the C++ 2011 standard regarding to functions std::begin and std::end. They can be simply substituted for

wdd and wdd + 3 correspondingly.

So you can rewrite the switch as

switch ( std::distance( wdd, std::find( wdd, wdd + 3, wd ) ) )
Last edited on
Topic archived. No new replies allowed.