R
R
rraderio2017-10-17 10:18:34
Programming
rraderio, 2017-10-17 10:18:34

What are variable flags for?

I just recently came across this term and I don't understand what they are for.
I'm not sure when to use the flag variable and how to do it?
If possible with examples in Java. Thank you.
boolean flag = false;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Pugachev, 2017-10-17
@Stqs

you don’t need to perceive flags as something super-specific or super-complex
it’s nothing more than an ordinary variable that affects the flow of a program
an example from life
you program all day at work and go home in the evening
let’s say that during the day your spouse can call and ask you to go to the store in the evening (sets the flag ENTER_TO_STORE = True)
at the end of the day this flag is checked - if it is True, then we will go to the store, if not, we will not enter
the nuances here:
- the flag can be set at ANY time
- the flag is not necessarily set by you yourself!
- Your reaction to the flag is not necessarily momentary
- before leaving home, it's better to call your wife and clarify the state of the flag :)
the flag does not have to be a Boolean variable, this concept is rather a logical one, for example, instead of the GO_TO_SHOP flag (in which it is not entirely clear what to buy), a smarter construction like ArrayListPurchaselist = {} can be used. At the beginning of the day the list is empty, during the day the wife remembers something - and adds things to the shopping list
at the end of the day you just check if the list is empty (there is no flag) - and then go home with a clear conscience
if there is at least something there (the flag is raised ) - You already know that 1) you need to go 2) what exactly you need to buy

A
Alexander, 2017-10-17
@NeiroNx

Variable flags are typically boolean global variables and are typically used to synchronize the execution of subroutines on different threads. The notion flag is set, flag is unchecked is equivalent to true and false.

V
VoidVolker, 2017-10-17
@VoidVolker

All other variables are used in the same way - for temporary or permanent storage of a logical value, passing it somewhere else, or storing the result of calling some function / procedure. For example WinAPI might return a boolean flag.

bool flag = true;
while(flag){
    flag = doSomeJob();
}

Or here's another real-life example - the "Dispose" pattern in C#:
private bool disposedValue = false; // Для определения избыточных вызовов

protected virtual void Dispose(bool disposing)
{
    if (!disposedValue)
    {
        if (disposing)
        {
            // TODO: освободить управляемое состояние (управляемые объекты).
        }

        // TODO: освободить неуправляемые ресурсы (неуправляемые объекты) и переопределить ниже метод завершения.
        // TODO: задать большим полям значение NULL.

        disposedValue = true;
    }
}

// TODO: переопределить метод завершения, только если Dispose(bool disposing) выше включает код для освобождения неуправляемых ресурсов.
// ~Cloud() {
//   // Не изменяйте этот код. Разместите код очистки выше, в методе Dispose(bool disposing).
//   Dispose(false);
// }

// Этот код добавлен для правильной реализации шаблона высвобождаемого класса.
public void Dispose()
{
    // Не изменяйте этот код. Разместите код очистки выше, в методе Dispose(bool disposing).
    Dispose(true);
    // TODO: раскомментировать следующую строку, если метод завершения переопределен выше.
    // GC.SuppressFinalize(this);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question