Search code examples
c++arraysindexingintshort

C++ Indexing an array of ints using a short


Ok guys I asked a question 15 mins ago and closed it because when I tried a simple test in main(), it worked. However, it does not work in the actual code:

Background, I have an array of unsigned ints which I cannot access via an unsigned short indexer. If I declare an array on the stack it works, but it doesnt work for my array data member.

Here is the array declaration:

typedef unsigned int uint;

class OB{
public:
    OB();
    void x(unsigned short side_pos);

private:
    uint best_p[2]; 
};

and here's the code where I get the compiler error:

void OB::x(unsigned short side_pos){
    unsigned int best_price = best_p[side_pos];
}

If I do:

void OB::x(unsigned short side_pos){
    unsigned short something_else = 1;
    unsigned int best_price = best_p[something_else];
}

I also get the compiler error, which is:

OB.cpp: In member function ‘void OB::x(short unsigned int)’:
OB.cpp:62:56: error: invalid types ‘unsigned int[short unsigned int]’ for array subscript
     unsigned int best_price = best_p[side_pos];

Solution

  • Based on intuition and comment hints, you have a local variable best_p (an unsigned int by the looks of it) that's shadowing the member of your class. Thus, best_p[side_pos] will use the local variable, not the data member.

    If you want the compiler to catch shadowing, the -Wshadow option should do it. The best thing to do when it does is rename something. Having a convention for data member names (m_<name> is a common one) can also help to prevent both accidental shadowing and thinking about what to rename something to.