vendredi 20 mars 2020

if else without parenthesis in C behaviour

I know I am missing something very basic, but why is it that I dont see anything displayed when I run this. (I was expecting the EINVAL print ).

#include<stdio.h>

unsigned int set_request(int val)
{
    printf("set_request entry\n");
    return 0;
}


void main()
{
    unsigned int val = 2;

    if (val == 0 || val == 1)
        if (set_request(val))
            printf("EIO\n");
    else
        printf("EINVAL\n");
}

jj@coffy:~/nvmemaster/tmp$ ./a.out
jj@coffy:~/nvmemaster/tmp$

I am getting the right behaviour when I add {} , but I would like to know the behaviour of if without {}

Alternatively if I modify the assignment line to 0 as shown below, then too I am seeing something odd. Now I wasn't expecting EINVAL printed.

#include<stdio.h>

unsigned int set_request(int val)
{
    printf("set_request entry\n");
    return 0;
}


void main()
{
    unsigned int val = 0;

    if (val == 0 || val == 1)
        if (set_request(val))
            printf("EIO\n");
    else
        printf("EINVAL\n");
}
jj@coffy:~/nvmemaster/tmp$ gcc if.c
jj@coffy:~/nvmemaster/tmp$ ./a.out
set_request entry
EINVAL
jj@coffy:~/nvmemaster/tmp$

Aucun commentaire:

Enregistrer un commentaire