Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I defined struct in the global scope, but when I try to use it, I get error: ‘co’ does not name a type, but when I do the same in a function, everything works fine

typedef struct {
  int x;
  int y;
  char t;
} MyStruct;

  MyStruct co;
  co.x = 1;
  co.y = 2;
  co.t = 'a'; //compile error

void f() {
  MyStruct co;
  co.x = 1;
  co.y = 2;
  co.t = 'a';
  cout << co.x << '' << co.y << '' << co.t << endl;
} //everything appears to work fine, no compile errors

Am I doing something wrong, or structures just cannot be used in global scope?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
103 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's not that you "can't use structures in global scope". There is nothing special here about structures.

You simply cannot write procedural code such as assignments outside of a function body. This is the case with any object:

int x = 0;
x = 5; // ERROR!

int main() {}

Also, that backwards typedef nonsense is so last century (and not required in C++).

If you're trying to initialise your object, do this:

#include <iostream>

struct MyStruct
{
   int x;
   int y;
   char t;
};

MyStruct co = { 1, 2, 'a' };

int main()
{
   std::cout << co.x << '' << co.y << '' << co.t << std::endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...