Tim MB
Tim MB

Reputation: 4521

Why do my map assignments cause a compiler error?

I can't get my head around why this won't compile:

#include <map>
#include <string>

std::map<std::string, std::string> m;
m["jkl"] = "asdf";

I receive this compiler error:

Line 5: error: expected constructor, destructor, or type conversion before '=' token compilation terminated due to -Wfatal-errors.

I swear I must be missing something simple here.

Upvotes: 2

Views: 221

Answers (2)

sepp2k
sepp2k

Reputation: 370435

m["jkl"] = "asdf" is an expression. You can't have an expression on its own outside of a function body. The only thing allowed outside of function bodies are declarations and definitions.

Upvotes: 5

dirkgently
dirkgently

Reputation: 111298

That assignment needs to be within a function (i.e. block scope). If you want to initialize the map then you will have to do so at the point of definition. Here is a related SO question (on initializing map at file-scope).

Upvotes: 2

Related Questions