AEDED
AEDED

Reputation: 21

Accessing enum Members in C

I have a function that is of type of a struct, which contains some integers and a reference to an enum, as such:

typedef struct Test {
    Error e;
    int temp;
    int value;
}Test;

Where the enum is:

typedef enum Error {
    IOError,
    ExternalError,
    ElseError,
}Error;

And say I have a function that wants to return an error (Of an enum of the 3), depending on if something happens.

Where the function is of type Test (I can't change any types or values passed in),

Why can't I return the error like this? How would I go about returning it (I can't change the struct definitions nor the function prototypes).

Test errorFunc() {

    return Test->e->IOError; //gives an error
}

Any help would be greatly appreciated!

Upvotes: 0

Views: 3478

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You don't need to, just do this

Error
errorFunc() 
{
    return IOError;
}

In there are no static struct members, nor namespaces so you just use the enum value1 directly.

Also, in you woudn't use the -> indirection operator for that instead you do something like this

class Test
{
public:
    enum Error
    {
        IOError
    };
};

And then you can have

Test::Error
errorFunc()
{
    return Test::IOError;
}

Which is apparently why you are confused.


1An enum is not a struct so technically it has no members

Upvotes: 2

srdjan.veljkovic
srdjan.veljkovic

Reputation: 2548

In C, you would code:

Test errorFunc() {
    return IOError;
}

This is C, everything is in the global namespace, there are no "strong" enums and enum "members" are basically "weakly typed integer constants". So, accessing a "data member" of an enum makes no sense. Just use the constant.

Compiler will check if the constant used is of the type you return and complain if it isn't. How much it will complain depends on the compiler, as enums are a little strange weak type concent (Stroustrup once called them "curiously half baked concept").

Upvotes: 1

Related Questions