🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Operators and conditions: if, switch and bitwise operators

Use arithmetic, comparison and logical operators; let the program decide with if/else and switch, and read the bits of a status byte with bitwise operators.

A battery charger measures the voltage and decides: "Is it full, should I charge, should I raise an alarm?" A motor driver looks at the bits in its status byte to find out whether there is an overcurrent. Decisions like these are the real work of a program. In this lesson we'll first look at arithmetic and comparison operators, then decision structures, and finally the bitwise operators that embedded software can't live without.

Arithmetic, comparison and logic

+ - * / are the operations you already know. % (modulo) gives the remainder of an integer division. Comparison operators (== != < > <= >=) produce 1 if true and 0 if false. Logical operators combine them: && (and), || (or), ! (not).

#include <stdio.h>

int main(void) {
    int sure_s = 3725;
    printf("%d saat %d dk %d s\n", sure_s / 3600, (sure_s % 3600) / 60, sure_s % 60);

    double v = 11.8;
    printf("v > 12.0 : %d\n", v > 12.0);
    printf("v >= 11.5 && v <= 12.6 : %d\n", v >= 11.5 && v <= 12.6);

    int sayac = 5;
    sayac += 3;     // sayac = sayac + 3
    sayac++;        // sayac = sayac + 1
    printf("sayac: %d\n", sayac);
    return 0;
}
1 saat 2 dk 5 s
v > 12.0 : 0
v >= 11.5 && v <= 12.6 : 1
sayac: 9

C has no separate "true" value: zero is false and anything non-zero counts as true. && and || short-circuit: in a && b, if a is false, b is never evaluated. Thanks to this, a condition such as r != 0 && v / r > 2 runs safely without dividing by zero.

if, else if, else

Let's print the approximate state of charge of a 12 V lead-acid battery from its resting voltage (the thresholds are for illustration):

#include <stdio.h>

int main(void) {
    double aku_v = 12.3;

    if (aku_v >= 12.6) {
        printf("Aku dolu\n");
    } else if (aku_v >= 12.2) {
        printf("Aku yari dolu\n");
    } else if (aku_v >= 11.8) {
        printf("Aku zayif, sarj et\n");
    } else {
        printf("KRITIK: aku bos\n");
    }
    return 0;
}
Aku yari dolu

Conditions are tried from top to bottom; the first true one runs and the rest are skipped. That's why ordering the thresholds from largest to smallest matters. Braces are not required for single-line bodies, but always writing them prevents mistakes when you add lines later.

Don't compare floating-point numbers with ==. In C, 0.1 + 0.2 == 0.3 gives 0 (false), because these numbers cannot be represented exactly in binary. Instead, check whether the difference is very small, or use >= / < thresholds as above.

switch: a multi-way decision

If you need to act on specific values of a single integer or character, like the mode of a multimeter, switch is more readable:

#include <stdio.h>

int main(void) {
    char mod = 'A';

    switch (mod) {
        case 'V': printf("Gerilim olcumu\n"); break;
        case 'A': printf("Akim olcumu\n");    break;
        case 'O': printf("Direnc olcumu\n");  break;
        default:  printf("Bilinmeyen mod\n"); break;
    }
    return 0;
}
Akim olcumu

break leaves the switch. If you forget it, the program "falls through" into the code of the next case and runs that too. default runs when no case matches. switch only works with integer types (including char); you can't switch on a double or on text.

An introduction to bitwise operators

On a microcontroller, one byte often carries eight separate pieces of information: each bit is an LED, a relay or an error flag. Bitwise operators are used to read and change them:

OperatorNameExample (binary)
&Bitwise AND0101 & 0011 = 0001
|Bitwise OR0101 | 0011 = 0111
^Exclusive OR (XOR)0101 ^ 0011 = 0110
~Complement (invert bits)~0101 = 1010 (for 4 bits)
<< / >>Shift left / right0001 << 2 = 0100

Suppose that in a motor driver's status byte, bit 0 means "running", bit 1 "overcurrent" and bit 2 "overtemperature". 1 << n produces a mask in which only bit n is 1; we test that bit with &:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint8_t durum = 0x05;              // 0000 0101

    if (durum & (1 << 0)) printf("Motor calisiyor\n");
    if (durum & (1 << 1)) printf("Asiri akim!\n");
    if (durum & (1 << 2)) printf("Asiri sicaklik!\n");

    printf("durum | 0x02 = 0x%02X\n", durum | 0x02);
    printf("durum ^ 0x01 = 0x%02X\n", durum ^ 0x01);
    printf("durum >> 1   = 0x%02X\n", durum >> 1);
    return 0;
}
Motor calisiyor
Asiri sicaklik!
durum | 0x02 = 0x07
durum ^ 0x01 = 0x04
durum >> 1   = 0x02

We'll look at the patterns for permanently setting, clearing and toggling bits in detail, with real register examples, in the last lesson of the course.

Common mistakes

Mixing up = and ==: if (t = 100) doesn't compare; it assigns 100 to t, and since the result is non-zero the condition is always true. -Wall warns about this.

  • Mixing up & and &&: & ANDs bits one by one, && combines two conditions. 1 & 2 is 0, while 1 && 2 is 1.
  • Forgetting break in a switch: unless it's intentional, the next case runs too and the bug becomes hard to find.

Exercise

Read a panel temperature (°C) from the user. Print "Donma riski" if it is below 0, "Normal" for 0-40, "Yuksek sicaklik" for 40-70 and "ALARM: fan ac" above 70.

Hint: build an else if chain and order the thresholds from smallest to largest: first t < 0, then t <= 40, then t <= 70.

Solution

#include <stdio.h>

int main(void) {
    double t;

    printf("Pano sicakligi (C): ");
    if (scanf("%lf", &t) != 1) {
        printf("Gecersiz giris!\n");
        return 1;
    }

    if (t < 0) {
        printf("Donma riski\n");
    } else if (t <= 40) {
        printf("Normal\n");
    } else if (t <= 70) {
        printf("Yuksek sicaklik\n");
    } else {
        printf("ALARM: fan ac\n");
    }
    return 0;
}
Pano sicakligi (C): 45
Yuksek sicaklik

Your program can now look at data, make decisions and read individual bits. In the next lesson we'll learn loops, which repeat the same job many times, and take the average of ADC readings.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. What is the value of 17 % 5?
2. What is the result of 0x0C & 0x0A?
3. What happens if a case in a switch has no break at the end?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.