Search code examples
c++bitset

What is "expected unqualified-id" error in C++?


Im trying to learn stl:bitmap, but I'm getting the following error: Headers added - bitset - string

Ive searched other SO posts for this error, but they are not related to bitset.

My Code

int main(){
    bitset<size> bs;
    bitset<10> bs2(45);
    bitset<13> bs3("1100101");

    cout << "bs: " << bs << endl;
    cout << "bs1: " << bs2 << endl;
    cout << "bs2: " << bs3 << endl;
    cout << endl;

    cout << "bs has " << bs.count() << " set bits" << endl;

    cout << bs.size() << endl;
    cout << bs2.size() << endl;
    cout << bs3.size() << endl;
}

My Error: Error in the last 3 cout statements.

$ g++ test.cpp 
test.cpp:28:16: error: expected unqualified-id
    cout << bs.size() << endl;
               ^
test.cpp:6:14: note: expanded from macro 'size'
#define size 16
             ^
test.cpp:29:17: error: expected unqualified-id
    cout << bs2.size() << endl;
                ^
test.cpp:6:14: note: expanded from macro 'size'
#define size 16
             ^
test.cpp:30:17: error: expected unqualified-id
    cout << bs3.size() << endl;
                ^
test.cpp:6:14: note: expanded from macro 'size'
#define size 16
             ^
3 errors generated.
$ 

Solution

  • You seem to have a macro defined in test.cpp line 6 which is string replacing your attempt to call the function size.

    Your line is actually saying:

    cout << bs.16() << endl;
    cout << bs2.16() << endl;
    cout << bs3.16() << endl;
    

    If you want to use macro's it's good practice to make them as descriptive as possible and use ALL_UPPER_CASE to avoid these type of issues.

    e.g. #define BITSET_DEFAULT_SIZE 16

    The error descriptions given to you by the compiler are very descriptive and let you know that a macro is the reason for this problem:

    test.cpp:28:16: error: expected unqualified-id
        cout << bs.size() << endl; <- this is telling you the starting position of the error
                   ^
    test.cpp:6:14: note: expanded from macro 'size'
        #define size 16 <- this is telling you a macro is involved, and giving its value
    

    Also, it's not good practice to use using namespace std in your programs due to std containing so many generic named functions. For example, if you create a function called size, you've suddenly overwritten std::size.

    Here is a good post pointing out why this is a bad idea