A flag is simply a variable which is used to represent the current state of a system, typically stored as a numeric value.
In regards to the predefined macros you have implemented in your current code:
Code:
#define flag_1 (0)
#define flag_2 (0)
#define flag_3 (0)
#define flag_1 (1)
#define flag_2 (1)
#define flag_3 (1)
The second group of macros actually redefined the previous group of macros for the symbols, flag_1, flag_2 and flag_3.
When the preprocessor encounters multiple definitions of the same symbol, only the macro immediately preceding the defined symbol is utilized to replace the symbol with macro replacement text. Such redefining of a macro, typically triggers a warning during preprocessor phase of compilation, unless a #undef is utilized to first undefine a symbol, before the redefining #define is encountered. Therefore, in the case of your current predefined macros arrangement, only the second set will have any effect during the preprocessor phase of compilation.
Flags are often utilized to implement a finite state machine (FSM), as in the following example:
Code C - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| #define state0 (0)
#define state1 (1)
#define state2 (2)
int main(void)
{
unsigned char stateflag = state0;
while(1)
{
switch (stateflag)
{
case state0:
// Perform Tasks Assigned to State0
stateflag = state1;
break;
case state1:
// Perform Tasks Assigned to State1
stateflag = state2;
break;
case state2:
// Perform Tasks Assigned to State2
stateflag = state0;
break;
default:
// Unknown State Encountered, Reset System to State0
stateflag = state0;
}
}
return (0);
} |
Similarly, an enumerated type (enum) can be utilized in place of the predefined macros, #define preprocessor directives, to implement the required system states:
Code C - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| enum sysstate {state0, state1, state2};
enum sysstate stateflag;
int main(void)
{
stateflag = state0;
while(1)
{
// __delay_ms(100);
switch (stateflag)
{
case state0 :
// Perform Tasks Assigned to State0
stateflag = state1;
break;
case state1 :
// Perform Tasks Assigned to State1
stateflag = state2;
break;
case state2 :
// Perform Tasks Assigned to State2
stateflag = state0;
break;
default:
// Unknown State Encountered, Reset System to State0
stateflag = state0;
}
}
return (0);
} |
BigDog