简体   繁体   中英

True and False with Operators

me again... Sorry for asking maybe a little bit stupid questions but i am a starter and i really want to learn coding.. So i got a problem to realize why those are always true? Its something with the operators or again C behavior is undefined. ?

   int x;
   int b;
   b = 1 < x < 10;
   printf("%d%d",b);
    char c = 'z';
    (c==' ') || (c='\t') || (c=='\n');
    printf("%c",c);

Why those are always true? Its because of ASCII code or what?

Result of comparison of constant 10 with boolean expression is always true

You can see here a table for the C Operator Precedences it could be read like this:

b = ((1 < x) < 10);

being that in languages such as C, relational operators return the integers 0 or 1, where 0 stands for false and any non-zero value stands for true.

so the value stored in b is 1 (true)

Also:

you're not initializing x , it should have trash info (probably != false)

and in your second code, you're allocating instead of comparing, (c='\t') is this on purpose? That's the reason it's printing a 'tab'.

In your first block of code, there are several problems:

  1. x is uninitialized (you did not give it a value)
  2. 1 < x < 10 is not valid C
  3. your printf statement expects 2 integer values to accompany the "%d%d", but you are only passing 1

I think this is what you want:

int x = <some valid value>;
int b;
b = ((1 < x) && (x < 10)); // expression is true if x is between [2..9]
printf("%d",b);

This line

(c==' ') || (c='\t') || (c=='\n');

Should be

(c==' ') || (c=='\t') || (c=='\n');

Note the double equals when comparing to \t (the tab character). Otherwise, you wind up assigning a tab char to c .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM