Emory King
Emory King

Reputation: 23

Undeclare structure member used in function?

My function definition won't compile because of a supposedly "undeclared" structure member. It says "error: ‘gen’ undeclared". But I declare it and even initialize it afterwards (I left that part out for simplicity). Can you see why this wont compile?

my structure:

typedef struct Parent {     
int gen;            //I DECLARE IT RIGHT HERE!!!
char *name;
struct Parent * next;
child * child;
} parent;

and my function:

void findP(parent* x){                  //function findP

    headP = p;
    tempC = headP->child;
    int check = 0;
    while(headP != NULL){
        while(tempC != NULL){
            if (x->name == tempC->name){
                x->gen = gen--;               //HERES WHERE I USE IT

                findP(headP);           //recursion here
                check++;
                break;
            }
            if(check > 0) break;
            tempC = tempC->next;
    }
        if(check > 0) break;
        headP = headP->next;
}
}

Upvotes: 0

Views: 84

Answers (3)

kfsone
kfsone

Reputation: 24259

You've declared gen but you've declared it as a member of struct Parent. Incidentally, you don't need the typedef infront of your struct declaration.

The reason this problem is not obvious is that you've fallen into a common trap of not making your struct/class member variables distinct. Many dev teams employ a best-practice of distinguishing member variable names with a leading m_, m or a trailing _. The m_ seems to be the most predominant way of doing this.

struct Parent {     
    int m_gen;            //I DECLARE IT RIGHT HERE!!!
    char * m_name;
    Parent * m_next;
    child * m_child;
};

typedef Parent parent; // if you're hell-bent on having both versions.

Now the problem should become very visible:

while(headP != NULL){
    while(tempC != NULL){
        if (x->m_name == tempC->m_name){
            x->m_gen = gen--;               //HERES WHERE I USE IT

gen is not a member of something, it's a local variable. If you add the m_ prefix

            x->m_gen = m_gen--;               //HERES WHERE I USE IT

then it's again quite clear, you haven't said "member of what" for the m_gen on the right hand side, and this is not a member function.

Upvotes: 0

sr01853
sr01853

Reputation: 6121

x->gen = gen--;

gen here in findP() is of course undeclared.

I think it is supposed to mean x->gen--;

Upvotes: 3

user2357112
user2357112

Reputation: 281252

x->gen = gen--;

x->gen exists. gen, though? What's the thing on the right? Did you mean the following?

x->gen--;

Upvotes: 2

Related Questions