A flag is a variable that is used to specify a particular condi-tion or status (see variable). Usually a flag is either true or false. For example, a flag Valid_Form could be set to true before the input form is processed. If the validation check for any data field fails, the flag would be set to false. After the input procedure has ended, the main program would check the Valid_Form flag. If it’s true, the data on the form is processed (for example, continuing on to the payment process). If the flag is false, the input form might be redis-played with errors or omissions highlighted.
Flags can be combined to check multiple conditions. For example, suppose the input form routine also looked up the customer’s account and checked to make sure the customer was approved for purchasing. The test for this might read:
If Valid_Form and Valid_Customer then
// continue processing else
// display error messages
In such cases, the flags are combined using the appro-priate and or or operators (see Boolean operators). While flags are often used inside a routine to keep track of processing, modern programming practice discourages the use of “global” flags at the top level of the program. As with other global variables, such flags are vulnerable to being unpredictably changed or to having two parts of the program check the same flag without being able to rely on its state. (Thus a routine relies on a global flag being true but calls another routine that sets the flag to false without the original routine checking it again.) If several routines (or even programs) are being run at the same time, the situ-ation gets even more complicated and a semaphore that can be controlled by one process at a time is more appropriate (see concurrent programming). However, a main pro-gram that sets a flag to indicate the program mode and does not allow the flag to be changed by routines within the pro-gram is relatively safe.
Flags can also have more than two valid conditions, such as for specifying a number of possible states for a file or device. This usage is found mostly in operating systems.
No comments:
Post a Comment