Quto
Quto

Reputation: 111

Why can't I declare structure 2nd time in function?

So, I got a function where I am declaring one structure which is filled and also want to declare one new function. When I declare new function on the top it works, when I declare it on the same line after comma (,) it works but it doesn't work on the bottom line. Any explanations? Thanks in advance.

void CFilter(float avgprofit, int lines)
{
    //client goodclient[MAX_CLIENT]; THIS WOULD COMPILE
    client client[MAX_CLIENT], goodclient[MAX_CLIENT]; // THIS COMPILES
    //client goodclient[MAX_CLIENT]; THIS WOULDN'T COMPILE
    int i, amount = 0;
    float userprofit;
    for (i = 0; i <= lines; i++) {
        userprofit = client[i].loses - client[i].wins;
        if (userprofit >= avgprofit) {
            client[i].goodclient = 1;
        } else {
            client[i].goodclient = 0;
        }
    }
}

Upvotes: 2

Views: 74

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

The problem is that the name of the array client hides the name of the type client.

client client[MAX_CLIENT];
client goodclient[MAX_CLIENT]; 

So in the second declaration the compiler considers the name client as the name of the array.

It is not a good idea to use the same name for different entities.

The simplest way to make the compiler to compile the declarations is to rename the array.

Or if the type client is a typedef of a structure type with the same name then you can write for example

client client[MAX_CLIENT];
struct client goodclient[MAX_CLIENT]; 

Another way is just to exchange the declarations

client goodclient[MAX_CLIENT]; 
client client[MAX_CLIENT];

Upvotes: 5

Related Questions