if (flag)

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    for (i = 0; i < m; ++i) 
    {
        flag = 1;
        for (j = 0; j < n; ++j) 
        {
            if (a2[i] == a1[j]) 
            {
                flag = 0;
                break;
            }
        }
        if (flag) {
            u[k] = a2[i];
            k++;
        }
    }
What kind of condition is this in the following line? Could someone please explain?

if (flag)
Last edited on
Write your answer here.

What do you mean "what kind of condition is this"?
Hello PK Dey,

The first thing to understand is whether it is an if condition, a for condition or the condition of a do/while or while loop they all evaluate to a bool type result.

So it does not matter how "flag" is defined. either a "bool" or an "int" it still ends up as a bool meaning that (0) zero is false and (1) is true. Any result that is not (0) zero is considered true and changed to a 1.

To look at it another way if (flag) is a shorthand for if (flag == 1) and for if (flag == 0) you would use
if (!flag).

Just like i++ is short for i = i +1 it is a way to better use what the language offers.

Andy
To look at it another way if (flag) is a shorthand for if (flag == 1) and for if (flag == 0) you would use
if (!flag).

Lot of Thanks Handy Andy!
Last edited on
Any time.
if (flag) is shorthand for (flag != 0)
if (!flag) is shorthand for (flag == 0)
C++: if(flag) is equivalent to if( bool(flag) ) ie. flag is contextually converted to bool
https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions

C: if(flag) is equivalent to if( flag != 0 ) ie. flag is compared with integer zero
https://en.cppreference.com/w/c/language/if
the reverse it true as well, boolean expressions result in integer 0 or 1 for false or true. This can be very handy.
Last edited on
Topic archived. No new replies allowed.