Using macro as a range in C. Nested Loops. Logic

92 Views Asked by At

I am trying to make this program which takes YYYY and MM from the user. I have defined macros outside the main function, which is kinda range for years to be taken as input. For months, i have declared JAN and DEC as 1 and 12 respectively. What I am trying to is,show an error when something(month and year) is out of range, and the loop should repeat untill the right input has been entered. I tried my best to do that, but i didnt get anything. here is my code.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define MIN_YEAR 2012
#define MAX_YEAR 2022


int main(void)
{
    const int JAN = 1;
    const int DEC = 12;
    int year = 0;
    int month = 0;


    do
    {
        printf("Set the year and month(YYYY MM): ");
        scanf(" %d %d", &year, &month);
            
        if ((MIN_YEAR > year && year > MAX_YEAR))
        {
            printf("ERROR: The year must be between 2012 and 2022 inclusive");
        }

        if ((JAN >= month >= DEC))
        {
            printf("ERROR: Jan.(1) - Dec.(12)");
        }

        else
        {
            printf("*** Log date set! ***");
        }

    } while (MIN_YEAR <= year <= MAX_YEAR , JAN <= month <= DEC);
   

    return 0;
}
1

There are 1 best solutions below

0
Vlad from Moscow On

This condition

if ((MIN_YEAR > year && year > MAX_YEAR))

is logically incorrect. It seems you mean

if ( year < MIN_YEAR || year > MAX_YEAR )

The condition in this if statement

    if ((JAN >= month >= DEC))

will always evaluate to false.

It is equivalent to

    if ( (JAN >= month ) >= DEC )

So the sub-expression (JAN >= month ) evaluates either to 0 or 1 that in any case is less than DEC.

It seems you mean

    if ( month < JAN || month > DEC )

In this condition

while (MIN_YEAR <= year <= MAX_YEAR , JAN <= month <= DEC)

there is used the comma operator. Its value is the values of the second operand JAN <= month <= DEC. That is as the first operand has no side effect then in fact the first operand MIN_YEAR <= year <= MAX_YEAR is ignored and does not influence on the result.

It seems you mean

while ( year < MIN_YEAR || year > MAX_YEAR || month < JAN  || month > DEC)

Also there is another logical error

    if ( ... )
    {
        printf("ERROR: The year must be between 2012 and 2022 inclusive");
    }

    if ( ... )
    {
        printf("ERROR: Jan.(1) - Dec.(12)");
    }

    else
    {
        printf("*** Log date set! ***");
    }

The else statements belongs to the second if statement. So even if the year was entered incorrectly but the month was specified correctly then the else statement gets the control.

You should write for example

    if ( ... )
    {
        printf("ERROR: The year must be between 2012 and 2022 inclusive");
    }

    else if ( ... )
    {
        printf("ERROR: Jan.(1) - Dec.(12)");
    }

    else
    {
        printf("*** Log date set! ***");
    }