2

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.

Tim MB
  • 4,413
  • 4
  • 38
  • 48

2 Answers2

5

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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 2
    `m["jkl"] = "asdf"` is an expression, `m["jkl"] = "asdf";` is a statement. Yes, since you ask, sometimes even I get bored of myself. – Steve Jessop Jun 12 '12 at 10:35
  • I had no idea that was the case. Guess I'd never tried it before. Thanks. – Tim MB Jun 12 '12 at 10:45
  • It would be nice if compilers could just tell that: "Statement found outside of function". It's a fairly common error, e.g. when you accidentily add a superfluous `}` to a function. – MSalters Jun 12 '12 at 11:09
2

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).

Community
  • 1
  • 1
dirkgently
  • 108,024
  • 16
  • 131
  • 187