0

I use Visual Studio Express 2013 and I try to run this code:

struct opcode {
    int length; 
};

std::map<int, struct opcode> opcodes;

opcodes[0x20] = {
    3
};

I get this error: error C2040: 'opcodes' : 'int [32]' differs in levels of indirection from 'std::map<int,opcode,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>'

And when I hover over opcodes I get this this declaration has no storage class or type specifier.

SOLUTION

The problem of mine was that I have put the statement outside the function.

7
  • 1
    You're missing the visual-studio, visual-studio-express and visual-studio-2013 tags for this question. :) Commented Aug 9, 2014 at 16:28
  • @jotik I'm not sure how much it matters. This is mostly a straight C++ question. Commented Aug 9, 2014 at 16:30
  • I have updated question tags. It seems really a visual studio related issue as from command line it's all good. @jotik, I have done it and no warnings given. Commented Aug 9, 2014 at 16:32
  • This is a long shot, but try std::map<int, opcode> opcodes; without the struct keyword. Maybe this confuses the compiler. Commented Aug 9, 2014 at 16:34
  • @jotik, no luck without struct keyword. Commented Aug 9, 2014 at 16:35

1 Answer 1

5

In C++ language statements - i.e. "the actual code" - have to reside inside functions. This

opcodes[0x20] = {
    3
};

is a statement. You cannot just throw it into a file without declaring a function. You cannot just write C++ code (i.e. statements) in the middle of the file.

All you can do in the "whitespace" between function is write declarations. So, you statement above was interpreted by the compiler as a declaration. Hence the strange error messages from the compiler.

If you intended this to be a statement, it should have looked as follows (for example)

int main()
{
  opcodes[0x20] = { 3 };    
}

However, you could achieve the same effect without a function by using an initializer, which is a part of declaration

std::map<int, struct opcode> opcodes = { { 0x20, { 3 } } };
Sign up to request clarification or add additional context in comments.

4 Comments

You've opened my eyes! Thanks!
@lukas.pukenis Maybe you want std::map<int, opcodes> opcodes = {{0x20, {3}}};
My problem was that I have put this outside the main() function(or any other) and as @AndreyT stated, statements cannot live alone
@lukas.pukenis I think you can still use std::map<int, opcodes> opcodes{{0x20, {3}}}; in namespace scope because it is a definition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.