← Retour au cours: C programming from scratch

Type conversions, constants and week 2 review

Vidéo bientôt disponible

When an expression mixes different types, C converts the values so it can operate on them. These automatic conversions are convenient, but sometimes they change the result without you noticing. Understanding them prevents subtle errors, especially in divisions and comparisons. In the second part of the lesson you will see how to name fixed values with const, #define and enum, and we will finish by reviewing the week.

Implicit conversions

The basic rules are two. First, types smaller than int (char, short) are promoted to int before operating. Second, if the two operands differ, the lower-rank one is converted to the higher: int becomes long, and any integer becomes double if the other is real. That is why 5 / 2 gives 2 but 5 / 2.0 gives 2.5. A dangerous case: when mixing signed int with unsigned, the negative value turns into a huge unsigned, and -1 < 1u turns out false.

c
#include <stdio.h>

int main(void) {
    int sum = 7, count = 2;

    double wrong = sum / count;            /* 3.0: integer division first */
    double right = (double)sum / count;    /* 3.5: cast before dividing */
    printf("wrong = %.1f, right = %.1f\n", wrong, right);

    int truncated = 9.99;                  /* becomes 9 */
    printf("truncated = %d\n", truncated);

    int negative = -1;
    unsigned int one = 1u;
    printf("-1 < 1u is %d\n", negative < one);   /* prints 0 */
    return 0;
}

Explicit conversions: the cast

A cast writes the type in parentheses before the value: (double)sum. Use it when you want to make clear that the conversion is intentional. Keep in mind that converting a real to an integer truncates toward zero, and that converting to a smaller type may lose information: an int of 300 converted to unsigned char gives 44. A cast does not fix a design error; it only tells the compiler you know what you are doing, so do not use them to silence warnings without understanding them.

Constants: const, #define and enum

A number written directly in the code, like 3.14159 or 365, is called a magic number, and it makes the program harder to understand and maintain. Give it a name. With const you declare a variable that cannot be modified after initialization and that has a type. With #define the preprocessor substitutes the text before compiling, with no type and no semicolon. With enum you define a group of related integer constants, ideal for states or options. Today const or enum is preferred over #define, because the compiler checks them.

c
#include <stdio.h>

#define MAX_NAME 32          /* preprocessor constant, no semicolon */

enum Color { RED, GREEN, BLUE };   /* RED=0, GREEN=1, BLUE=2 */

int main(void) {
    const double pi = 3.14159265358979;
    const int radius = 5;
    /* pi = 3.0;   error: assignment of read-only variable */

    double area = pi * radius * radius;
    printf("Area: %.2f\n", area);

    enum Color c = GREEN;
    printf("Color code: %d, name buffer size: %d\n", c, MAX_NAME);
    return 0;
}

Review of week 2: you can now operate with arithmetic, compare and combine conditions, read data with scanf checking its result and limiting text, control type conversions and name fixed values. Before moving on to the quiz, do the exercise: it gathers almost everything you learned into a small program.

Testez vos acquis

Question 1 sur 6

What is 7 / 2 in C with integers?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →