• Home
  • 3.14 Truth Value of Integer Expressions

3.14 Truth Value of Integer Expressions

View Categories

3.14 Truth Value of Integer Expressions

< 1 min read

Table of Contents

In C, an integer expression can be used as a condition. The value 0 represents false, while any non-zero value represents true.

#include <stdio.h>

int main()
{
    int a = 0;
    int b = 10;
    int c = -5;

    if (a)
    {
        printf("a is true\n");
    }

    if (b)
    {
        printf("b is true\n");
    }

    if (c)
    {
        printf("c is true\n");
    }

    return 0;
}

Example Output #

b is true
c is true

Explanation #

The value of a is 0, so it represents a false condition:

if (a)

The values of b and c are non-zero, so both represent true conditions:

if (b)
if (c)

This rule also applies to integer expressions:

if (10 - 10)
{
    printf("True\n");
}

10 - 10 produces 0, so the block is not executed.

if (10 - 5)
{
    printf("True\n");
}

10 - 5 produces 5, which is non-zero, so the block is executed.

In C, integer expressions used as conditions do not need to produce specifically 0 or 1; zero is false and any non-zero value is true.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *