0

In a switch statement for C++, I believe you are allowed to use either int or char in the switch. For my purposes, I want to use a char. The char I want to use is the a char from a string. Here is my function:

#include <string>
using namespace std;
...
int calindex(string* seq)
{
    int index = 0;
    for(int i=0;i<seq.length();i++)
    {
      switch(seq[i])
      {
      ...
      }
    }
return index; // index is modified within the switch statement
}

However, when I compile I get an error for the line: "switch(seq[i]" that states "switch quantity not an integer". Can anyone see what I did wrong?

1
  • Well the first error I see is the use of seq.length() when seq is a pointer.
    – David G
    Commented Jul 3, 2013 at 19:42

6 Answers 6

3
switch(seq[i])

should be:

switch((*seq)[i])

You forgot to dereference the pointer first. It's trying to access the ith string. Also:

seq.length();

should be:

seq->length();
0
1

The case values in a switch statement need to be compile-time constant. The point of a switch statement is to have a sort of fast, efficient cascading if statement. The compiler does special stuff to the switch statement to make it fast, but to do that, it needs to know at compile-time what all of the cases are.

0

seq is a string *, not a char *, so seq[i] has type string.

In C++, string is preferred over char arrays, and likewise, references are preferred over pointers, so change the declaration of your argument to

string &seq

so that string::operator [] can take effect and return a (reference to) char.

(You can declare seq as char * too, but then that's C and not C++...)

0

It is correct to index the string and switch by a char value, but the problem is that you're no indexing a string, but a pointer to a string. Then you should dereference the pointer, but why don't you use a string on the first place?

0

You're passing a string pointer to calindex, but you treat seq as if you passed a string either by value or by reference.

In order to make your switch statement work, you need to dereference the pointer in one of two ways:

(*seq)[i]

or

seq->at(i)

Please note that the latter will throw an exception if you try to access a non-existing element, the former won't.

0

The problem here is passing by pointer:

int calindex(string* seq)

Why dont you use:

int calindex(string& seq)

Its more safe to do it in that way.

The most important is that you do not have to make a precondition to check if pointer is zero

With reference you would not make such a simple mistake like omitting dereferencing.

Not the answer you're looking for? Browse other questions tagged or ask your own question.