enum in c programming

Thread Starter

vead

Joined Nov 24, 2011
629
Hello
I need help to understand use of enum in c programming . enum consist set of constant integer, Using the enum keyword, we can declare an enumeration type with using the enumeration tag and a list of named integer. following example describe declaration of enum in c programming
Code:
enum task
{
task_1,
task_2,
task_3
}
I think if we do not assign the value to the enumeration constant then compiler automatically assign the 0 to the first member of the list and increase these value by 1. compiler assign first 0 to constant member of enumeration list exampe task_1=0, than value will increase by 1 task_2=1 and task_3=2
when do we use enum in program and what does following program?
Code:
typedef enum
{
task_1 =0,
task_2,
task_3
}my_state_t;
my_task_t task = task_1;
 
Last edited:

nsaspook

Joined Aug 27, 2009
13,265
The enum in your example is just a easy human-readable way to define and manipulate the machine state in a sometimes non-sequential manner. When the state can be defined as just a sequential increase in a number as the next state a regular variable can be used like in this simple round-robin task example.
C:
void work_handler(void)
{
static int8_t task = 0;

if (PIR1bits.TMR1IF) {

PIR1bits.TMR1IF = LOW; // clear TMR1 interrupt flag
WriteTimer1(PDELAY);
/*
* task work stack
*/
switch (task) {
case 0:
if (hid0_ptr->bled_on) {
hid0_ptr->t_on();
} else {
hid0_ptr->t_off();
}
break;
case 1:
if (hid1_ptr->bled_on) {
hid1_ptr->t_on();
} else {
hid1_ptr->t_off();
}
break;
default:
task = -1; // null task
break;
}
task++;
}
}
A more complex enum task state example for a Bluetooth LE application. As the device state changes (appData.state) in the switch different tasks are executed.
https://github.com/nsaspook/fac_relay_clone
C:
// data structures from app.h
typedef enum {
  APP_INITIALIZE = 0, // Initialize application
  APP_INITIALIZATION_ERROR, // Initialization Error
  APP_BLUETOOTH_ADVERTISE, // Advertise the bluetooth connection, not connected
  APP_BLUETOOTH_PAIRED, // Bluetooth module is paired to server, we idle
  APP_SLEEP // Sleep mode
} APP_STATE_T;

typedef struct {
  APP_STATE_T state; //APP_Tasks state
  char receive_packet[BT_RX_PKT_SZ]; //message buffers
  char transmit_packet[BT_TX_PKT_SZ];
  bool got_packet, //new packet flag
  update_packet,
  sendSwitches, //new switch states ready to send
  ADCcalFlag, //ADC is calibrated if true
  led1, led2, led3, led4, led5, led6, //LED states
  oled1, oled2, oled3, oled4;
  int8_t error_code;
  volatile bool sw1, sw2, sw3, sw4, //switch states
  sw1Changed, sw2Changed, sw3Changed, sw4Changed, //switch state has changed
  RTCCalarm, //RTCC alarm has tripped
  accumReady, //ADC accumulator is done
  ADCinUse, //ADC or accumulator register is currently in use
  timer1Flag, //Timer1 has tripped
  CNint, //CN interrupt has tripped (flag to exit sleep)
  sleepFlag; //sleep mode triggered
  uint16_t potValue, potValueOld, potValueLastTX, version_code; //potentiometer values - current, previous, and last transmitted, firmware version
  struct LINK_DATA *packet_data;
} APP_DATA;

//

APP_DATA appData;
ADC_DATA adcData;

//Primary application state machine

void APP_Tasks(void)
{
#ifdef USE_SLEEP  //see config.h, Application setting section
APP_STATE_T savedState;
int16_t potDiff;

//Has inactivity timer expired?
if (appData.sleepFlag) {
savedState = appData.state; //Save context
appData.state = APP_SLEEP; //Enter sleep state
}
#endif

//Update LED outputs
LED_Tasks();

switch (appData.state) {
//Initial state
case APP_INITIALIZE:
if (APP_Initialize()) {
appData.state = APP_BLUETOOTH_ADVERTISE;
} else {
appData.state = APP_INITIALIZATION_ERROR;
}
break;

//Initialization failed
case APP_INITIALIZATION_ERROR:
LED_SET_LightShow(LED_ERROR);
break;

//We're not connected to a device - advertise mode
case APP_BLUETOOTH_ADVERTISE:
LED_SET_LightShow(LED_BTLE_ADVERTISING);
if (BT_CONNECTED) {
appData.state = APP_BLUETOOTH_PAIRED;
}
break;

//We are connected to a BTLE device
case APP_BLUETOOTH_PAIRED:
//Update LEDs
LED_SET_LightShow(LED_BTLE_PAIRED);
//Check to see if we are still connected; return to advertise state if not
if (!BT_CONNECTED) {
appData.update_packet = false;
LED_SET_LightShow(LED_BTLE_ADVERTISING);
appData.state = APP_BLUETOOTH_ADVERTISE;
break;
}

//Check if switches have changed and debounce timers are expired
Switch_Tasks();
if (appData.sendSwitches) { //New switch status to send?
//Form message
sprintf(appData.transmit_packet, "suw,"PRIVATE_CHAR_SWITCHES",%d%d%d%d\r", appData.sw1, appData.sw2, appData.sw3, appData.sw4);
//Try to transmit the message; reset flag if successful
if (BT_SendCommand(appData.transmit_packet, true)) {
appData.sendSwitches = false;
}
}

//Process ADC accumulator value if oversampling is complete
if (appData.accumReady) {
ADC_ProcAccum();
#ifdef USE_SLEEP  //see config.h, Application setting section
potDiff = appData.potValue - appData.potValueOld; //Reset the inactivity sleep timer if pot has changed
if (potDiff > POT_KEEP_AWAKE_DELTA || potDiff < -POT_KEEP_AWAKE_DELTA) {
SleepTimerReset();
}
#endif
appData.accumReady = false; //Clear app flags
appData.ADCinUse = false;
}

//Start new ADC read if timer expired, not currently sampling, and not waiting to process accumulator
if (TimerDone(TMR_ADC) && appData.ADCinUse == false) {
if (ADC_Tasks()) {
StartTimer(TMR_ADC, ADC_REFRESH_MS);
} //Restart timer once module is up and running
}

//Transmit new potentiometer reading?
if (TimerDone(TMR_POT)) {
//Send message only if pot value has changed
if (appData.potValue != appData.potValueLastTX) {
//Form message
sprintf(appData.transmit_packet, "suw,"PRIVATE_CHAR_POTENTIOMETER",%04d\r", appData.potValue);
//Try to transmit the message; reset timer if successful
if (BT_SendCommand(appData.transmit_packet, true)) {
appData.potValueLastTX = appData.potValue;
StartTimer(TMR_POT, POT_TX_MS);
}
} else {
StartTimer(TMR_POT, POT_TX_MS);
} //value not changed - skip this transmission
}

//Process any new messages received from RN module
appData.got_packet = BT_ReceivePacket(appData.receive_packet); //Get new message if one has been received from the RN4020
if (appData.got_packet == true) { //true if new packet received

appData.packet_data = Get_Link_Packet();
appData.packet_data->dac1 = appData.potValue & 0xff;
appData.packet_data->dac2 = appData.potValue >> 8;
Write_Link_Packet((uint8_t *) appData.packet_data, true);

if (strstr(appData.receive_packet, "WV,001E,")) { //Check for LED update message 1.23
GetNewLEDs(); //Latch new LED values
appData.update_packet = true;
}
if (strstr(appData.receive_packet, "WV,0021,")) { //Check for LED update message 1.33
GetNewLEDs(); //Latch new LED values
appData.update_packet = true;
}
//
//Other message handling can be added here
//
//receive new SPI ADC channel
if (strstr(appData.receive_packet, "WV,0025,")) {
GetNewADC_Chan(); // new ADC config data
}
//receive new SPI SLAVE request
if (strstr(appData.receive_packet, "WV,0027,")) {

}
}
break;

#ifdef USE_SLEEP  //see config.h, Application setting section 
//Put micro and RN module to sleep - any button press will cause wake up
case APP_SLEEP:
appData.sleepFlag = 0; //clear flag and call sleep function
APP_SleepNow();
appData.state = savedState; //Woken from sleep; restore state
break;
#endif //USE_SLEEP

default:
break;
} //end switch(appData.state)
} //end APP_Tasks()
 

Thread Starter

vead

Joined Nov 24, 2011
629
The enum in your example is just a easy human-readable way to define and manipulate the machine state in a sometimes non-sequential manner. When the state can be defined as just a sequential increase in a number as the next state a regular variable can be used like in this simple round-robin task example.
Your example is very complex for me. I tried to make simple example. suppose I want blink three LED's with different times
I am writing this code. this just for basic understanding of enum statement. does it make any sense ?
Code:
typedef enum
{
task_1 =0,
task_2,
task_3
}my_state_t;
my_task_t task = task_1;

void LED1_delay (unsigned int i)
{
    unsigned int j;
    for (i = 0; i < 1000; i++)

void LED2_delay (unsigned int j)
{
    unsigned int j;
    for (j = 0; j < 1500; j++)
void LED3_delay (unsigned int k)
{
    unsigned int k;
    for (k = 0; k < 1200; k++)
int main ()
{
unsigned int task;
switch(task)
{
case 1:
if (my_task_t task = task_1)
LED1 = LED1_ON;
LED1_delay(1000);
LED1 = LED1_OFF;
break;
case 2:
if (my_task_t task = task_2)
LED2 = LED2_ON;
LED2_delay(1500);
LED2 = LED2_OFF;
breaks(); //Stop

case 3:
if (my_task_t task = task_3)
LED3 = LED3_ON;
LED1_delay(1200);
LED3 = LED3_OFF;
}
 
Last edited:

WBahn

Joined Mar 31, 2012
30,052
Hello
I need help to understand use of enum in c programming . enum consist set of constant integer, Using the enum keyword, we can declare an enumeration type with using the enumeration tag and a list of named integer. following example describe declaration of enum in c programming
Code:
enum task
{
task_1,
task_2,
task_3
}
I think if we do not assign the value to the enumeration constant then compiler automatically assign the 0 to the first member of the list and increase these value by 1. compiler assign first 0 to constant member of enumeration list exampe task_1=0, than value will increase by 1 task_2=1 and task_3=2
when do we use enum in program and what does following program?
Code:
typedef enum
{
task_1 =0,
task_2,
task_3
}my_state_t;
my_task_t task = task_1;
You've created an enumerated type named "my_state_t".

Then you declare a variable of type "my_task_t".

Have you bothered to try running this code at all?
 

Thread Starter

vead

Joined Nov 24, 2011
629
Why don't you test it with your compiler and maybe a hardware board.
as you suggested. I tried to compile following code but I am getting one error. can you tell me my mistakes in program?
Code:
#include<reg51.h>    //header file
sbit LED1 = P2^0;    //LED 1 conncted to port P2 pin 0
sbit LED2 = P2^1;    //LED 2 conncted to port P2 pin 1
sbit LED3 = P2^2;    //LED 3 conncted to port P2 pin 2

typedef enum
{
task_1 =0,
task_2,
task_3
}my_task_t;
my_task_t task = task_1

// functions to make LED's ON/OFF

void LED_1_ON()       // LED1 should be ON
{
LED1= 1;
}

void LED_1_OFF()     // LED1 should be OFF
{
LED1= 0;
}

void LED_2_ON()      // LED2 should be ON
{
LED2= 1;
}

void LED_2_OFF()     // LED2 should be OFF
{
LED2= 0;
}

void LED_3_ON()      // LED3 should be ON
{
LED3= 1;
}

void LED_3_OFF()     // LED3 should be OFF
{
LED3= 0;
}

//delay for LED's

void LED1_delay (unsigned int i)       // Delay for LED1
{
    unsigned int j;
    for (i = 0; i < 1000; i++)

void LED2_delay (unsigned int j)        // Delay for LED2
{
    unsigned int j;
    for (j = 0; j < 1500; j++)
void LED3_delay (unsigned int k)         // Delay for LED3
{
    unsigned int k;
    for (k = 0; k < 1200; k++)
int main ()
{
unsigned int task;
switch(task)
{
case 1:
if (my_task_t task = task_1)
LED_1_ON();
LED1_delay(1000);
LED_1_OFF();
break;

case 2:
if (my_task_t task = task_2)
LED_2_ON();
LED2_delay(1500);
LED_2_OFF();
breaks(); //Stop

case 3:
if (my_task_t task = task_3)
LED_3_ON();
LED3_delay(1200);
LED_3_OFF();
}
}
error
function.c(20): error C141: syntax error near '}'
function.c(54): error C141: syntax error near 'void'
function.c - 6 Error(s), 0 Warning(s).
 
Last edited:

WBahn

Joined Mar 31, 2012
30,052
It says six errors. You've only shown two. What is the first error?

Focus on the first error -- the others may or may not be real. Look first at the line number that is reported. If you don't see the error on that line, then it is probably on the line above it, but could be several lines earlier.

You need to start being able to look at your code and at least find glaring errors for yourself.

You know that C statements end with semicolons.

You know that functions are defined by code enclosed in curly braces.

You have several of these and then many other errors, both syntax errors and logical errors.

Try to find as many as you can and clean them up.

It would also help enormously if you took the time to properly indent your code.
 

Thread Starter

vead

Joined Nov 24, 2011
629
It says six errors. You've only shown two. What is the first error?

Focus on the first error -- the others may or may not be real. Look first at the line number that is reported. If you don't see the error on that line, then it is probably on the line above it, but could be several lines earlier.

Try to find as many as you can and clean them up.

.
Thanks for helping me. I have removed some error but still there are some errors
Code:
#include<reg51.h>    //header file
sbit LED1 = P2^0;    //LED 1 conncted to port P2 pin 0
sbit LED2 = P2^1;    //LED 2 conncted to port P2 pin 1
sbit LED3 = P2^2;    //LED 3 conncted to port P2 pin 2
typedef enum
{
task_1 =0,
task_2,
task_3
}my_task_t;
my_task_t task = task_1;

// functions to make LED's ON/OFF
void LED_1_ON()       // LED1 should be ON
{
LED1= 1;
}
void LED_1_OFF()     // LED1 should be OFF
{
LED1= 0;
}
void LED_2_ON()      // LED2 should be ON
{
LED2= 1;
}
void LED_2_OFF()     // LED2 should be OFF
{
LED2= 0;
}
void LED_3_ON()      // LED3 should be ON
{
LED3= 1;
}
void LED_3_OFF()     // LED3 should be OFF
{
LED3= 0;
}
//delay for LED's
void LED1_delay (unsigned int i)       // Delay for LED1
{
    unsigned int i;
    for (i = 0; i < 1000; i++)
}
void LED2_delay (unsigned int j)        // Delay for LED2
{
    unsigned int j;
    for (j = 0; j < 1500; j++)
}
void LED3_delay (unsigned int k)         // Delay for LED3
{
    unsigned int k;
    for (k = 0; k < 1200; k++)
}
int main ()
{
unsigned int task;
switch(task)
{
case task_1:
if(my_task_t task = task_1)
{
LED_1_ON();
LED1_delay(1000);
LED_1_OFF();
break;
}
case task_2:
if (my_task_t task = task_2)
LED_2_ON();
LED2_delay(1500);
LED_2_OFF();
breaks(); //Stop
case task_3:
if (my_task_t task = task_3)
LED_3_ON();
LED3_delay(1200);
LED_3_OFF();
}
}
I am facing problem in this part
Code:
int main ()
{
unsigned int task;
switch(task)
{
case task_1:
if(my_task_t task = task_1)
{
LED_1_ON();
LED1_delay(1000);
LED_1_OFF();
break;
}
case task_2:
if (my_task_t task = task_2)
LED_2_ON();
LED2_delay(1500);
LED_2_OFF();
breaks(); //Stop
case task_3:
if (my_task_t task = task_3)
LED_3_ON();
LED3_delay(1200);
LED_3_OFF();
}
}
there is 8 errors but my compiler showing only two errors. I am using keil compiler. I am trying to remove below Errors. I have seen some example on internet and tried to fix myself. but I don't know whats wrong in code
function.c(70): error C141: syntax error near 'my_task_t'
function.c(78): error C141: syntax error near 'my_task_t'
function.c - 8 Error(s), 0 Warning(s).
 
Last edited:

ErnieM

Joined Apr 24, 2011
8,377
When compiling C code it is often the case one error will propagate down causing further errors. Also sometimes the line(s) proceeding a flagged error are whatis causing the errors.

So generally when tracking down errors fix the first one you see, then try recompiling. Oft time to your surprise and delight many other errors will be solved. If not... again attack the first error till you get a clean compile.

The code you posted is incredibly hard to read as you did not do any indentation for blocks of code. That is a big no-no. Also, you split the code up so the line numbers in the post do not match what the compiler saw, so we cannot tell what line triggers the error.

In line 11 of the first code blob you define task of type my_task and set to task_1. That is good, but later when you go to use task you keep,putting the typedef my_task in front of task. No good, delete that!

Later is your second blob you have a switch statement for task. Good. But on every switch you again try to compare the switch variable task to the state that MUST be true because that is why you switched to that block. So delete those redundant (and incorrect) if statements.
 

Thread Starter

vead

Joined Nov 24, 2011
629
Hello again
Now I am trying to solve another errors. I think there is something wrong in delays function. reason may be multiple time delay
Code:
#include<reg51.h>  //header file
sbit LED1 = P2^0;  //LED 1 conncted to port P2 pin 0
sbit LED2 = P2^1;  //LED 2 conncted to port P2 pin 1
sbit LED3 = P2^2;  //LED 3 conncted to port P2 pin 2
typedef enum
{
task_1 =0,
task_2,
task_3
}my_task_t;
my_task_t task = task_1;
// functions to make LED's ON/OFF
void LED_1_ON()  // LED1 should be ON
{
LED1= 1;
}
void LED_1_OFF()  // LED1 should be OFF
{
LED1= 0;
}
void LED_2_ON()  // LED2 should be ON
{
LED2= 1;
}
void LED_2_OFF()  // LED2 should be OFF
{
LED2= 0;
}
void LED_3_ON()  // LED3 should be ON
{
LED3= 1;
}
void LED_3_OFF()  // LED3 should be OFF
{
LED3= 0;
}
//delay for LED's
void LED1_delay ()  // Delay for LED1
{
  unsigned int i;
  for (i = 0; i < 1000; i++)
}
void LED2_delay ()  // Delay for LED2
{
  unsigned int j;
  for (j = 0; j < 1500; j++)
}
void LED3_delay ()  // Delay for LED3
{
  unsigned int k;
  for (k = 0; k < 1200; k++)
}
int main()
{
unsigned int task;
switch(task)
{
case task_1:
if(task == 0)
{
LED_1_ON();
LED1_delay();
LED_1_OFF();
break;
}
case task_2:
if (task = 1)
LED_2_ON();
LED2_delay();
LED_2_OFF();
breaks(); //Stop
case task_3:
if (task = 2)
LED_3_ON();
LED3_delay();
LED_3_OFF();
}
}
function.c(42): error C141: syntax error near '}'
function.c(47): error C141: syntax error near '}'
function.c(52): error C141: syntax error near '}'
 
Last edited:

ErnieM

Joined Apr 24, 2011
8,377
Same error three times.

As we suggested look at the line ABOVE where the compiler flags an error. In each case here y have an unterminated for loop.

Add a semi ; at the end of each for line so the compiler knows you are ending the for loop right there.
 

MrChips

Joined Oct 2, 2009
30,802
When using control structures such as if-else, while, for, etc.,
always use { } to create code blocks even if it is blank. This will keep you out of trouble.
Also learn to make your code pretty by indenting your code blocks.

For example:

Code:
if ( enabled )
  {
  }
else
  {
  }

do
  {
      if ( button_pressed )
        {
        }
      else
        {
        }
  }
while ( valid );

while ( running )
  {
      for ( i = 0; i < n; i++)
        {
        }
  }

switch (colour)
{
   case red:
    {
      break;
    }
   case blue:
    {
      break;
    }
   default:
    {
    }
}

switch (colour)
{
   case red:
      break;
   case blue:
      break;
   default:
}
The switch-case structure is one place where you can leave out the { }.
Don't forget the break; statement to terminate each case block.

Note that the for statement needs to be terminated:
Code:
    for ( i = 0; i < n; i++)
      {
      }

    for ( i = 0; i < n; i++);
 

WBahn

Joined Mar 31, 2012
30,052
Thanks for helping me. I have removed some error but still there are some errors

there is 8 errors but my compiler showing only two errors. I am using keil compiler. I am trying to remove below Errors. I have seen some example on internet and tried to fix myself. but I don't know whats wrong in code
You are making it very difficult for anyone to help you. You won't properly indent your code. You give us code snippets which make it so that we can't tell what line an error is referring to. When you get an error that starts with "function.c(70):" it means that the error was recognized in line 70 of the file function.c. But WE have NO idea what line is line 70 unless you indicate which line is line 70 or post the code starting from the beginning of the file.

So properly INDENT your code and for each line number given in the error list, add a comment after that line indicating which line it is so that we can look at the line the compiler is complaining about.
 

nsaspook

Joined Aug 27, 2009
13,265
Why are you making your code so complicated?

This is better:
Code:
LED1 = ON;
  delay(LED1_DELAY);
LED1 = OFF;
Sadly it's complicated because he's parroting code examples instead of taking the time to learn basic C programming, syntax and concepts. My lost hope was that he would look at some enum examples and realize that he needs to actually look at and understand the information in every C programming book about the language but it seems that's too much to ask for.
 

spinnaker

Joined Oct 29, 2009
7,830
Whenever I have one of these odd issues that is hard to track down the actual error, I start by copying the original file then start taking out code until I narrow down to the section or line causing the actual issue.As mentioned above, a mistake tell up into the code can cause an error much further down in the code.

Also macros are notorious for causing errors that are hard to track down.
 

MrChips

Joined Oct 2, 2009
30,802
What do you mean by indent your code. does it means include numbers for each lines. I have posted code with lines and numbers. you can see error in line number. can you tell me what you all telling me about indent code?
Look at my code examples in posts #13 and #14.
Do you see anything different from the code you have posted?
 

MrChips

Joined Oct 2, 2009
30,802
okay I understood. your code is readable, anyone can understand easily. I think indent code will not work on real design. I think it will only help to understand logic , it will not work on real project. I was reading this link https://www2.cs.arizona.edu/~mccann/indent_c.html I have to write code in that style to understand easily. I am trying to write c program for three LED's using different time delay because I want to learn use of enum, case and switch statement. when I look the example for enum, case and switch statement. I understand but when I try to write in one program for real project I am facing problem.
What do you mean that it will not work on real projects?

Millions upon millions of real computer projects are written in code using indents.
 
Top