Question

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
};
Was it helpful?

Solution

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. [...]

OTHER TIPS

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

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}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top