简体   繁体   中英

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;
        }
    }
}

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM