Home > Net >  undeclared identifier error with a structure in C
undeclared identifier error with a structure in C

Time:09-13

I have a structure ST_transaction_t that contains 2 structures, an enumeration and uint32_t members, when I declare the structure ST_transaction account1 I get account1': undeclared identifier error. When I remove the enumeration typed member from the structure it works.

Here is the part of the code with the problem:

typedef struct ST_transaction_t
{
    ST_cardData_t cardHolderData;
    ST_terminalData_t terminalData;
    EN_transState_t transState;
    uint32_t transactionSequenceNumber;
}ST_transaction_t;
typedef enum EN_transState_t
{
    APPROVED, DECLINED_INSUFFECIENT_FUND, DECLINED_STOLEN_CARD, INTERNAL_SERVER_ERROR
}EN_transState_t;

int main() {
ST_transaction_t account1 ;
return 0;
}

Now if did this:

typedef struct ST_transaction_t
{
    ST_cardData_t cardHolderData;
    ST_terminalData_t terminalData;
    //EN_transState_t transState;
    uint32_t transactionSequenceNumber;
}ST_transaction_t;
typedef enum EN_transState_t
{
    APPROVED, DECLINED_INSUFFECIENT_FUND, DECLINED_STOLEN_CARD, INTERNAL_SERVER_ERROR
}EN_transState_t;

int main() {
ST_transaction_t account1 ;
return 0;
}

It works perfectly, so why is that EN_transState_t transState causing that error and how to fix it ?

CodePudding user response:

you problem is not about variable called EN_transState_t transState; itself, rather it's about its typedef place in the code , I mean when the compiler compiles your code line by line and comes to this line EN_transState_t transState; , there is no previous declaration of such a type , as the declaration of such a type is mentioned in later lines meaning that EN_transState_t transState; comes before these lines:

   typedef enum EN_transState_t
   {
        APPROVED, DECLINED_INSUFFECIENT_FUND, DECLINED_STOLEN_CARD, INTERNAL_SERVER_ERROR 

    }EN_transState_t;

so you have to :

typedef enum EN_transState_t
{
    APPROVED, DECLINED_INSUFFECIENT_FUND, DECLINED_STOLEN_CARD, INTERNAL_SERVER_ERROR
}EN_transState_t;

typedef struct ST_transaction_t
{
    ST_cardData_t cardHolderData;
    ST_terminalData_t terminalData;
    EN_transState_t transState;
    uint32_t transactionSequenceNumber;
}ST_transaction_t;


int main() {
ST_transaction_t account1 ;
return 0;
}

CodePudding user response:

In your code typedef enum EN_transState_t is only declared after its use in typedef struct ST_transaction_t. In C all types must be declared before it can be referenced. The compiler works from the top down.

Move the declaration typedef enum EN_transState_t to before typedef struct ST_transaction_tand your code should work.

  • Related