in Programming in C
495 views
0 votes
0 votes
i was trying a program with macros and wanted to throw compile time error. I resolved my program however on further studying i am confused with the use of logical operator. Please help me to understand this

for the following program with && operator output shown is "successfully  Performed"

#include <stdio.h>

int main() {
   int age=15;

   #if (age>5) && (age>10)   /*replace && with || and check for different combination of relational operator*/
   #error cannot perform this operation
   #endif
   printf("successfully performed");
   return 0;
}

the same output is produced if we replace (age>10) with (age<10). BUT if i use logical OR || operator this will throw the #error.

Why is this so? is it undefined behaviour of compiler?
in Programming in C
495 views

2 Comments

@Ananya Jaiswal 1,Since you've used '||' operator and accordingly, either of the condition should be true.Accordingly, your (age>5) is true,but the second part isn't. Your code should've executed. Even my compiler is giving the #error part. Which compiler you've used?I executed the code in Ubuntu.
0
0
i'm also using ubuntu. 14.04 gcc 4.8
0
0

1 Answer

0 votes
0 votes

Heard of short circuiting? 

for || - as soon as it got any statement true (from LHS to RHS) compiler  will not check further and will returns true; else false;

for && -as soon as it got statement false (from LHS to RHS) compiler  will not check further and will returns false; else true;

Hope it help.

2 Comments

but if i'm doing like this thn also it is giving error. this should not produce error according to short circuiting. am  i correct?

int main() {
   int age=15;

   #if (age>5) || (age<10)   /*replace && with || and check for different combination of relational operator*/
   #error cannot perform this operation
   #endif
   printf("successfully performed");
   return 0;
}
0
0

ok finally got answer #if can only contain constant expression. Now what is constant expression see https://stackoverflow.com/questions/3755524/example-of-something-which-is-and-is-not-a-constant-expression-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

#if definition reference https://www.cs.auckland.ac.nz/references/unix/digital/AQTLTBTE/DOCU_078.HTM

another one https://gcc.gnu.org/onlinedocs/cpp/If.html

but how compiler is working with non constant expression i don't know.

2
2

Related questions