Wednesday, April 22, 2015

C language from BaseBand Processor Eng perspective Part-5 Enums

Enums seems to be quite straightforward in the way we use in most of our codes.

Many a times we even don't need them.

But in modem code we extensively use them, let me take a scenario

The voice call you make seems to very easy from UI or what option comes ar screen. You simply swaps the number and call is made.

But Call itself has some types example

Voice Call,
Data Call ,
Emergency call,
Fax Call  etc

Now whenever call request will come , we have to check call type.

For that we can't simply write the below code

#define VOICE_CALL 1
#define DATA_CALL 2
#define EMER_CALL 3
#define FAX_CALL 4

the disadvantage been if tomorrow a new call type is added and we have to add it in between we have to change all the #defines.

So  we use enums for that

typedef enum{
VOICE_CALL=1,
DATA_CALL,
EMER_CALL,
FAX_CALL
}call_type;

Now we all know how to go on using this code .

ex

if( firstcall.call_type == VOICE_CALL)  do this ......

1) Now while working some example , I found that below is not allowed in C but allowed in CPP



typedef enum{
VOICE_CALL=1,
DATA_CALL,
EMER_CALL,
FAX_CALL
}call_type;


typedef enum{
VOICE_CALL=12,
DATA_CALL,
EMER_CALL,
FAX_CALL
}call_type_more;

In C and CPP  , we can't have same constant define in two different enums with same scope .

In above code both enums are global and hence will give error saying all the variables inside them are redefined.

But in case we define one enum inside main function and one global, no COMPILE ERROR, but again CPP we can access them using below

call_type_more :: VOICE_CALL.

but no such scope resolution operator in C.



2) Also call_type  here is a data type , which will take only values inside in it.

ex

call_type var1 = 2;  // this will throw error
call_type var2 = VOICE_CALL ; // this only will work

but while comparing  we can compare  enum type to integers.

if( 2== var2 ) do this....

Also we can compare two different enums.

if(var1 == var2)








No comments:

Post a Comment