Enumerated constants

Status
Not open for further replies.

PA3040

Advanced Member level 3
Joined
Aug 1, 2011
Messages
883
Helped
43
Reputation
88
Reaction score
43
Trophy points
1,308
Visit site
Activity points
6,936
Dear all

Thai is related to ENUMERATED CONSTANTS and MCU is 16f877a

In assembly

Code:
#define   UP       PORTB,0
#define   DOWN PORTB,1
#define   LEFT    PORTB,2
#define   RIGHT  PORTB,3

in MicroC

Code:
enum MOTORS {UP, DOWN, LEFT, RIGHT}; // Declare constant MOTORS

Could you please, can any one teach me the different between above two

Is it both are same but different language? Am I correct ?

Please advice
thanks in advance
 

No, they are quite different.

The #define is actually very simple, all it does is substitute one name for another. It sometimes has a facility to pass other text into it as well but basically, using your assembly code, every time you use 'UP' in your program it will substitute 'PORTB,0' instead. You can see this if you look at the listing file from the assembler where you should see it has inserted 'PORTB,0' everywhere you originally type 'UP'. It's a way of making your program more readable and easier to edit, for example if you decide to change the port bits for UP and DOWN you can edit the define statements and reassemble without having to go all the way through the program looking for and changing every ocurrence of PORTB,0 and PORTB,1.

The enum is a C quick way of numbering a list. You could use UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3 and so on but when they are increasing by 1 each time it's simpler to just put them in a list and let the compiler do it for you. The numbers normally start at zero but you can force a jump in them by assigning a value inside the list, for example "enum MOTORS (UP, DOWN, LEFT = 7, RIGHT)" would give them the values 0, 1, 7 and 8. You will find enums are very useful when you have many items in the list, especially if you have to add an extra item somewhere in the middle. To do that with an enum you just edit the list and recompile, if you did it by assigning a value to each item you would have to edit all the subsequent numbers because they would be out of step.

Brian.
 
Reactions: PA3040

    PA3040

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…