Kerkiko
Kerkiko

Reputation: 31

Can I use an if statement as condition in another if statement in C?

Can I do that? I´ve searched for an answer, but I couldn´t found any. What I want to do is this:

if(a==5)
{
   printf("25");
}

if((if(a==5))==TRUE)
{
    printf("\n30");
}

Is this permissible in C?

Upvotes: 0

Views: 158

Answers (2)

Can I use an if statement as condition in another if statement in C?

No, you can´t do that, it isn´t syntactically correct. You would get this or a similar error for the inner if test, if you would attempt to compile code that has any occurrence of that in its source code:

error: expected expression before 'if'

But it is already redundant since you can proof several expressions inside just one if statement´s condition test by using the logic operators &&(AND) and ||(OR):

int a = 5;
int b = 10;

if(a == 5 && b == 10)     // If a is 5 AND b is 10. - true
{
    /* some code */
}

or

int a = 6;
int b = 10;

if(a == 5 || b == 10)     // If a is 5 OR b is 10. - true
{
    /* some code */
}

Given your example:

if(a==5)
{
   printf("25");
}

if((if(a==5))==TRUE)
{
    printf("\n30");
}

The inner if statement inside the condition of the outer if statement - if((if(a==5)) == TRUE) isn´t permissible but also redundant, because an if statement proofs on its own whether the condition or a sub-expression is true or not.

Thus, if((if(a==5)) == TRUE), if((a==5) == TRUE) and if(a==5) would be all equivalent, if a if condition test inside the condition of another were permissible and the if statement shall somehow be evaluated to 1.

So even in this surreal case, the code in the example would be equivalent to:

if(a==5)
{
   printf("25");
   printf("\n30");
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

This

if(a==5)
{
   printf("25");
}

if((if(a==5))==TRUE)
{
    printf("\n30");
}

can be rewritten this way with keeping the same logic

int condition;

if( ( condition = a == 5 ) )
{
   printf("25");
}

if( condition )
{
    printf("\n30");
}

Upvotes: 0

Related Questions