比較演算子
C言語の比較演算子について解説します。C言語の比較演算子は、左辺と右辺の数値を比較します。
比較演算子の一覧
比較演算子の一覧です。
| 演算子 | 解説 |
|---|---|
| == | 左辺と右辺は等しい |
| != | 左辺と右辺は等しくない |
| > | 左辺は右辺より大きい |
| >= | 左辺は右辺より大きいまたは等しい |
| < | 左辺は右辺より小さい |
| <= | 左辺は右辺より小さいまたは等しい |
比較演算子は、条件を満たした場合はint型の「1」、満たさなかった場合は「0」を返します。これはC言語の仕様で、どの処理系でも同じです。
数値の大小を比較する
数値の大小を比較してみましょう。
int32_t型の数値の大小比較
比較演算子を使って数値の大小を比較してみましょう。int32_t型どうしの比較を行うサンプルです。
#include <stdint.h>
#include <stdio.h>
int main(void) {
int32_t num1 = 15;
int32_t num2 = 10;
if (num1 > num2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
int64_t型の数値の大小比較
比較演算子で、int64_t型どうしの比較を行うサンプルです。
#include <stdint.h>
#include <stdio.h>
int main(void) {
int64_t num1 = 15;
int64_t num2 = 10;
if (num1 > num2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
int32_t型とint8_t型の数値の大小比較
比較演算子で、int32_t型とint8_t型の比較を行うサンプルです。
#include <stdint.h>
#include <stdio.h>
int main(void) {
int32_t num1 = 15;
int8_t num2 = 10;
if (num1 > num2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
C言語では二項演算子の両辺は、int型よりも小さな型の場合は、int型に拡張されるという規則があります。また両辺の型の大きさが異なる場合は、小さな型の値が、大きな型の値に変換されます。
処理系のintのサイズが仮に16bitであったとして、上記の記述を、明示的な型キャストを使って書き直してみましょう。
まずint8_t(符号あり8bit整数)は、int(符号あり16bit整数)に変換され、さらにint32_t(符号あり32bit整数)に変換されます。
#include <stdint.h>
#include <stdio.h>
int main(void) {
int32_t num1 = 15;
int8_t num2 = 10;
// 明示的に型キャストを書くと
if (num1 > (int32_t)(int)num2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
他の型の場合でも暗黙的な型変換の規則は同じです。型の大きさには順序があって「double」「float」「int64_t」「int32_t」「int16_t」「int8_t」の順番になることを覚えておきましょう。
uint32_t型の数値の大小比較
比較演算子を使って数値の大小を比較してみましょう。uint32_t型どうしの比較を行うサンプルです。
#include <stdint.h>
#include <stdio.h>
int main(void) {
uint32_t num1 = 15;
uint32_t num2 = 10;
if (num1 > num2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
符号あり整数と符号なし整数の比較はお勧めしない理由
符号なし整数と符号あり整数の比較は、お勧めしないです。意図していない暗黙の型変換が発生している場合があるので、明示的に型キャストして、比較することをお勧めします。
float型どうしの比較
比較演算子で、float型の比較を行うサンプルです。
#include <stdint.h>
#include <stdio.h>
int main(void) {
float num1 = 15.5f;
float num2 = 10.2f;
if (num1 > num2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
double型どうしの比較
比較演算子で、double型の比較を行うサンプルです。
#include <stdint.h>
#include <stdio.h>
int main(void) {
double num1 = 15.5;
double num2 = 10.2;
if (num1 > num2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
ポインタどうしの比較
ポインタを比較してみましょう。ポインタにはアドレスが代入されていますが、アドレスというのは数値です。C言語の比較演算子は数値を比較しますが、アドレスが同じかどうかという判定も比較演算子で行うことができます。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// ポインタ
int32_t* nums1 = calloc(sizeof(int32_t), 10);
int32_t* nums2 = nums1;
if (nums1 == nums2) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
free(nums1);
}
ポインタとNULLの比較
ポインタとNULLを比較してみましょう。NULLは0と等価ですので、比較演算子で比較できます。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// ポインタ
int32_t* nums1 = calloc(sizeof(int32_t), 10);
// ポインタがNULLではない
if (nums1 != NULL) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
free(nums1);
}
C言語ゼミ


