Struct declaration question?

Code 1

#include <iostream>
#include <string>
using namespace std;

struct data
{
string name;
}a,b;

int main()
{
cin >> a.name;
cout << a.name << endl;
cin >> b.name;
cout << b.name << endl;
return 0;
}


Code 2

#include <iostream>
#include <string>
using namespace std;

struct data
{
string name;
};

int main()
{
data a,b;

cin >> a.name;
cout << a.name << endl;
cin >> b.name;
cout << b.name << endl;
return 0;
}


I used to program in C. And i use to declare struct like in the Code 1. But in C++, i often see struct being declared like in Code 2. My question is, is it bad practice to declare struct in C++ like in Code 1 instead of Code 2.

And btw, i find it that its easier to declare struct in Code 1.
Last edited on
The difference is in the scope of the Objects. Code 1 declares them globally, while Code 2 declares them locally (in main). For this code, it obviously makes no real difference, but in bigger programs you'll want to avoid globally defined variables.
Thanx @Gaminic.
Topic archived. No new replies allowed.