1

If I use this code outside of a method or winmain:

ostringstream vertexid;
vertexid << "bob";

vertexid << " ";
vertexid << " ";

vertexid << 48348093490;

I get all sorts of syntax errors. How does scope play into this why is this happening?

Greg G
  • 697
  • 2
  • 8
  • 17

3 Answers3

2

You can do something like this:

std::ostringstream ss;

#define nil(x) ((x), 0)
int x = nil(ss << "Hello");
int y = nil(ss << ", World!");
int z = nil(ss << std::endl);

If you really don't like thinking up variable names, then you can do something even crazier:

#define nilPASTE(x, y) x ## y
#define nilPASTE2(x, y) nilPASTE(x, y)
#define nil2(x) static int nilPASTE2(line_, __LINE__) = nil(x)
nil2(ss << "Goodbye");
nil2(ss << ", Sun!");
nil2(ss << std::endl);

You asked:

How does scope play into this why is this happening?

I assume you mention scope because that is what some error message spat out. But the answer to both parts of that question is that the C++ compiler is following the rules of the C++ language, which does not allow statements to just appear anywhere. They can only appear where they are allowed, which are in functions and method bodies. The reason my technique is allowed is because I am using expressions, and expressions can appear in more places. In particular, they are allowed to appear in an initializer to a variable. And of course, variable declarations are allowed on the outer most level of a translation unit.

All that gobbly gook means: put your statements inside functions and methods.

jxh
  • 69,070
  • 8
  • 110
  • 193
1

You can only declare or define stuff at global scope.

The first line alone would be OK (in an implementation file... if in a header, you risk having multiple definitions and would need to declare it as extern instead of defining it), the next lines are just not legal.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
-2

At global namespace you cannot have code, because when should it be executed? You can only put executable statements inside functions, for example WinMain/main.

The execution starts at WinMain/main, then you can call your other functions from there.

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
  • You can call functions before main - http://stackoverflow.com/a/10897576/673730 - and you can have code at global namespace - see user315052's answer. – Luchian Grigore Jun 19 '12 at 08:16
  • 1
    I know, but these overcomplications don't help the guy who asked the question, this is just geek talk. – unkulunkulu Jun 19 '12 at 08:17
  • If you look at my answer, you'll see that I avoid these "overcomplications" without providing **false** information - yes, your statements are false. – Luchian Grigore Jun 19 '12 at 08:22
  • 1
    I know it. but it's a white lie. I looked at your answer tbh and decided to provide mine, cause you throw these redefinition things at him while he obviously doesn't know more basic things, it didn't look very helpful to me. – unkulunkulu Jun 19 '12 at 08:24