Skip to content

Instantly share code, notes, and snippets.

@ryohji
Last active November 7, 2020 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryohji/7d7be732e273f689203930aaece67d2d to your computer and use it in GitHub Desktop.
Save ryohji/7d7be732e273f689203930aaece67d2d to your computer and use it in GitHub Desktop.
not operator in C

C 言語の not 演算子には2種類ある。 ~!。論理学では ~ を否定で使うことが多いけれど C 言語での論理否定は !~ はビットごとの否定。

ビットごとの否定

// bitwise-not.c
#include <stdbool.h>

int main() { return ~false; }

$ make bitwise-not && ./bitwise-not; echo $? # ==> 255

false の定義は 0 (int) のため、これをビットごとに否定すると -1 になる。 main の戻り値 int はシェルで1バイトに切り詰められるため exit code を $? で参照して表示すると 255 になる。

論理否定

// logical-not.c
#include <stdbool.h>

int main() { return !false; }

$ make logical-not && ./logical-not; echo $? # ==> 1

論理否定をとると 1 が表示される。 ただしわたしの記憶が確かならば C 言語での false の論理否定は 0 でない値という定義だったはずで、処理系依存。

ここでは ~! の否定の結果の値は異なることがある、ということが確かめられたという程度の話。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment