LoginSignup
1
2

More than 5 years have passed since last update.

いつまでも覚えられない && と ||

Last updated at Posted at 2014-12-27

考えたら負けかなと思ってる。

演算子&&は最初の非演算子が偽ならその時点で評価は偽になる。
続く非演算子を評価するまでもないからわざわざ評価されない。

よけいな計算はしねぇよ!というC言語の粋なはからいである。
評価されない式?しらねぇよ!というC言語の粋なはからいである。
ありがたいのか、めんどくさいのか、よくわからん奴・・・。

a && b; ・・・ a がゼロなら評価は偽(if not "a" then...)

a & b ・・・ a,b ともに非ゼロなら評価は真(if "a" and only if "b" then...)

a || b ・・・ a が 非ゼロなら評価は真(if "a" then...)

a | b ・・・ a か b のどちらかが非ゼロなら評価は真(either "a" or "b"...)


int a = 0;
int b = -1;

/* a は ゼロであるが 真なので getchar()は呼ばれない */
if(a && (b=getchar()) { puts(b); }

/* a は 非ゼロであるということはない が 真なので if文はつづく・・ */
if(!a && (b=getchar()) { puts(b); }

/* a は 非ゼロであるが 真なので getchar()が呼ばれる */
if(a || (b==getchar()) { ... }

/* a は 非ゼロであるということはない が 真なので if文はつづかない */
if(!a || (b==getchar()) { ... }

Memo(追記)

int c, i=0;
char v[10];

whlie(i<10-2 && (c=getchar()!= EOF) && c!='\n') {
    v[i++] = c;
    ....
}
i<10-2
    10-2 : 8
    i<8  : true or false

(c=getchar()!=EOF)
    getchar() : ?
    c=?
    c : ?
    c!=EOF : true or false

c!='\n'
   c!='\n' : true or false

token1 && token2 && token3
    token1 && token2 : true or false
    left expression && token3
while((c=getchar()!='\n') && c!= 'x') ...
  getchar()
  c
  c!='\n'
  -> c && c : '\n' && 'x'

改行か 文字x のどちらかを読み取った時点で終了

while(c=getchar()!='\n') && t!='x') { 
    c=t;
    ....
}
    getchar()
    c
    t!='\n'
    -> c && t : 

比較するオブジェクトが異なることに注意

int c,t;
while((c=fgetc(src))!= EOF && t!='\n') t=c;

/* src が 改行文字を手当する場合、改行を見つけた時点で終了。
配列や入力デバイス。通常ファイルも同様。 */

int c,t;
while((c=fgetc(src))!= EOF || t!='\n') t=c;

/* src が 改行文字を手当する場合、改行で終了。改行がなければEOFまで。
配列や入力デバイス。通常ファイルも同様。 */

1
2
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2