Omkant
Omkant

Reputation: 9204

enum is constant or const varibale or anything else ? getting error in the following code

#include<stdio.h>

typedef enum {a,b,c}key;

int main()
{
 key d=3;
 printf("%p\n,&a);
 printf("%p\n",&d);
 printf("%d\t %d\t %d\t %d\n",a,b,c,d);
 return 0;
}

When I try to get the address of either a or b or c Compiler throws an error that lvalue required for unary &

I didn't get it because it's working for d of same type. What's happening here ? are these constants or the const varibales assigned with values 0 1 and 2 by the compiler. Beacause this kind of error we got for constants only. Please help , I am new to C

Upvotes: 0

Views: 1209

Answers (4)

Jeyaram
Jeyaram

Reputation: 9474

An enum is just like an integer type, with the added bonus of having a bunch of named literals. An enumeration comprises a set of named integer constant values.

From C standard C99. Section 6.7 Semantics, point 3:

for an enumeration constant or typedef name, is the (only) declaration of the identifier.

so it just a declaration. no memory will be allocated.

Upvotes: 0

Mike
Mike

Reputation: 49433

Check out what an enum really is. It's a value. Remember if you don't initialize an enum list the first one is given the value of 0.

Consider the boolean enum example:

typedef enum /* Declares an enumeration data type called BOOLEAN */
{
    false,     /* false = 0, true = 1 */
    true 
}BOOLEAN ; 

So the enum "false" is 0. You can't take the address of 0, but if you make a "BOOLEAN" from this:

BOOLEAN something = false; 

Now something is a variable and you can take the address of that.

Upvotes: 4

Maksim Skurydzin
Maksim Skurydzin

Reputation: 10541

The members of enums are constants (just like 3, 1000, or 'b'), hence can only be used as rvalues. They don't have any locations in memory.

But d is a variable whose value is one of enum members (not necessarily though). d has a well defined memory location and can be used as lvalue (we can take it's address, modify it etc).

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25705

a,b,c are symbols for constant-integers within an enum. They're not variables to have an address. Hence & cannot be used here(which means only rvalue).

Upvotes: 1

Related Questions