2

Is it possible to declare variables with the same name into different structs? For example:

struct first
{
    int a;
    int b;
    int the_same;
};

struct second
{
    int x;
    int y;
    int the_same
};
ᴜsᴇʀ
  • 1,109
  • 2
  • 9
  • 23

3 Answers3

4

Yes, they work well as they belong to different code scopes. You can access them by first.the_same and second.the_same.

[...] Scope is an important component of name resolution, which is in turn fundamental to language semantics. Name resolution (including scope) varies between programming languages, and within a programming language, varies by type of entity. Together with namespaces, scoping rules are crucial in modular programming, so a change in one part of the program does not break an unrelated part. [...]

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
1

Yes you can use the variable with same name in different structure.

struct first
{
    int a;
    int b;
    int the_same;
};

Hear a,b and the_same are element of structure first. and in structure

struct second
{
    int x;
    int y;
    int the_same
};

x,y and the_same are element of structure second.

compiler will refer this variable with there structure name not individually..

Abhitesh khatri
  • 2,911
  • 3
  • 20
  • 29
0

It's possible to do so. You may have thought that It's like Enums which if you have same values in 2 different enums you'll get a compile time error but that would be possible if enums namespace differ. for example:

namespace a {
   enum a { a, b, c }

}

namespace b {
   enum a {a, b, c}
}
Novin Shahroudi
  • 620
  • 8
  • 18
  • what is a namespace? I only know C and have never heard of such a thing. – Grady Player Jan 19 '14 at 18:30
  • Oh sorry about that. Namespaces are a feature added in C++. It's intention is to create new scopes in the code. – Novin Shahroudi Jan 19 '14 at 18:35
  • @NOVIN In C, the correct name for namespaces is *overloading classes* – Filipe Gonçalves Jan 19 '14 at 18:50
  • @FilipeGonçalves As far as I know the concept of classes doesn't exist in C99 neither C11. And also in C++ namespaces have their own concept and as far as I know there's no such thing as overloading classes but "class operator(or function) overloading" – Novin Shahroudi Jan 19 '14 at 18:55
  • @Grady Player C has "_name spaces_". See C11 `6.2.3 Name spaces of identifiers`. – chux - Reinstate Monica Jan 19 '14 at 19:17
  • @NOVIN As I said, the correct name is *overloading classes*, and if you don't believe me, you should read *C: A Reference Manual* (5th ed.), and have a look at Section 4.2.4. And no one talked about classes and C++, the fact that the word *class* shows up just got you confused ;) – Filipe Gonçalves Jan 19 '14 at 21:26
  • @chux nice try at getting me on a technicality, but that is totally irrelevant. – Grady Player Jan 19 '14 at 23:36