Ciência da computação · Livro 3 · Graduação — Ano 1

University Computer Science — Year 1

Este livro ainda não está disponível em Português. Edições: English.

University Computer Science — Year 1 · Graduação — Ano 1

2C: Types, Operators and Control Flow

A countdown from 3 to 0 is four lines of C. The program below prints 3, 2, 1, 0, and then 4294967295, and would go on for ever if a guard did not stop it. Nothing is wrong with the processor: the counter was declared unsigned, an unsigned number is never below zero, and one step below zero is the largest unsigned number. In Python an integer grows as large as it needs to; in C every number has a fixed width, and the rules that follow from that width are the subject of this chapter.

#include <stdio.h>

int main(void)
{
    int guard = 0;                       // stops the demonstration after 6 turns
    for (unsigned i = 3; i >= 0; i--) {
        printf("%u\n", i);
        if (++guard == 6) {
            puts("... and so on, forever");
            break;
        }
    }
    return 0;
}
Listing 2.1. A countdown that never reaches the end code/bachelor-1/02-c-types-and-control/listings/countdown.c
$ gcc -std=c17 -O2 -Wall -Wextra -o countdown countdown.c -lm && ./countdown
countdown.c: In function 'main':
countdown.c:7:28: warning: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]
    7 |     for (unsigned i = 3; i >= 0; i--) {
      |                            ^~
3
2
1
0
4294967295
4294967294
... and so on, forever
Output 2.1. The compiler warned; the loop went past zero.

You already know

A machine integer has a fixed number of bits NN. Read as an unsigned number, the bits stand for a value in [0,2N−1][0, 2^N - 1]; read in two’s complement, for a value in [−2N−1,2N−1−1][-2^{N-1}, 2^{N-1} - 1], the leading bit having weight −2N−1-2^{N-1}. A floating-point number holds a sign, an exponent and a significand, so that 0.10.1 is stored rounded. The school volumes showed both in Python, which hides the widths.

2.1 Integer types and their widths

Definition 2.1 (Integer type, width)

An integer type of C is a set of whole numbers stored in a fixed number of bits, its width: char, short, int, long and long long, each signed (two’s complement) or unsigned. The standard only sets minimum widths (8, 16, 16, 32 and 64 bits); each machine chooses the real ones. The header <stdint.h> adds types of an exact width: int8_t to int64_t, and uint8_t to uint64_t.

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

int main(void)
{
    printf("char       %zu byte,  %d .. %d\n", sizeof(char), CHAR_MIN, CHAR_MAX);
    printf("short      %zu bytes, %d .. %d\n", sizeof(short), SHRT_MIN, SHRT_MAX);
    printf("int        %zu bytes, %d .. %d\n", sizeof(int), INT_MIN, INT_MAX);
    printf("long       %zu bytes, %ld .. %ld\n", sizeof(long), LONG_MIN, LONG_MAX);
    printf("long long  %zu bytes\n", sizeof(long long));
    printf("unsigned   %zu bytes, 0 .. %u\n", sizeof(unsigned), UINT_MAX);
    printf("int8_t %zu, int16_t %zu, int32_t %zu, int64_t %zu\n", sizeof(int8_t),
           sizeof(int16_t), sizeof(int32_t), sizeof(int64_t));
    printf("a pointer  %zu bytes, size_t %zu bytes\n", sizeof(void *), sizeof(size_t));
    return 0;
}
Listing 2.2. Asking the machine for its widths code/bachelor-1/02-c-types-and-control/listings/sizes.c
$ gcc -std=c17 -O2 -Wall -Wextra -o sizes sizes.c -lm && ./sizes
char       1 byte,  -128 .. 127
short      2 bytes, -32768 .. 32767
int        4 bytes, -2147483648 .. 2147483647
long       8 bytes, -9223372036854775808 .. 9223372036854775807
long long  8 bytes
unsigned   4 bytes, 0 .. 4294967295
int8_t 1, int16_t 2, int32_t 4, int64_t 8
a pointer  8 bytes, size_t 8 bytes
Output 2.2. The widths on this machine: int 32 bits, long and pointers 64 bits.

This 64-bit Linux machine follows the convention called LP64: long and pointers are 64 bits, int stays at 32. Another system may differ (on 64-bit Windows, long is 32 bits), which is why a program that needs an exact width says int32_t or uint64_t, and why sizeof, the operator that gives the size of a type in bytes, appears in portable code instead of a constant. On a fixed width, arithmetic must do something with results that do not fit.

Definition 2.2 (Integer overflow)

An integer overflow happens when the exact result of an operation on integers lies outside the range of its type. For unsigned types C defines the result: it is the exact result modulo 2N2^N, so unsigned arithmetic never overflows in the language’s sense, it wraps. For signed types the behaviour is undefined (Section 2.5).

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

int main(void)
{
    uint8_t small = 250;
    small = small + 10;                  // 260 mod 256
    unsigned big = UINT_MAX;
    big = big + 1;                       // 2^32 mod 2^32
    unsigned below = 0;
    below = below - 1;                   // -1 mod 2^32
    printf("250 + 10 in 8 bits     = %u\n", (unsigned)small);
    printf("UINT_MAX + 1           = %u\n", big);
    printf("0 - 1 in unsigned int  = %u\n", below);
    return 0;
}
Listing 2.3. Unsigned arithmetic wraps code/bachelor-1/02-c-types-and-control/listings/wrap.c
$ gcc -std=c17 -O2 -Wall -Wextra -o wrap wrap.c -lm && ./wrap
250 + 10 in 8 bits     = 4
UINT_MAX + 1           = 0
0 - 1 in unsigned int  = 4294967295
Output 2.3. Three computations modulo 282^8 and 2322^{32}.
#include <limits.h>
#include <stdio.h>

int main(void)
{
    int x = INT_MAX;
    int y = x + 1;                       // undefined behaviour
    printf("INT_MAX + 1 gave %d\n", y);
    return 0;
}
Listing 2.4. Signed arithmetic does not: built with the undefined-behaviour sanitizer code/bachelor-1/02-c-types-and-control/listings/overflow.c
$ gcc -std=c17 -O0 -fsanitize=undefined -o overflow overflow.c -lm && ./overflow
overflow.c:9:9: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
INT_MAX + 1 gave -2147483648
Output 2.4. The sanitizer reports the overflow, then the program goes on.

The option -fsanitize=undefined makes the compiler add checks around risky operations; at run time each check that fails prints a report with the file, line and column. Here the program printed −2147483648-2147483648 afterwards, the two’s complement wrap, but nothing obliged it to: the next section explains why.

The 256 bit patterns of an 8-bit integer on a circle, adding 1 turning clockwise. Each pattern has an unsigned reading (outside) and a two’s complement reading (inside). Unsigned arithmetic wraps between 255 and 0; signed arithmetic has its seam between 127 and -128, and crossing it is undefined behaviour in C.
The 256 bit patterns of an 8-bit integer on a circle, adding 1 turning clockwise. Each pattern has an unsigned reading (outside) and a two’s complement reading (inside). Unsigned arithmetic wraps between 255 and 0; signed arithmetic has its seam between 127 and −128-128, and crossing it is undefined behaviour in C.

2.2 Floating types and characters

C’s double is the binary64 format seen in the school volume: 53 significant bits, so about 16 decimal digits. Every decimal fraction that is not a sum of powers of two is rounded when stored, and the rounding errors of an addition do not cancel: 0.1 + 0.2 is not 0.3. A program never compares computed floating values with ==; it compares with a tolerance, relative to the size of the numbers.

#include <math.h>
#include <stdio.h>

int nearly_equal(double a, double b, double rel)
{
    return fabs(a - b) <= rel * fmax(fabs(a), fabs(b));
}

int main(void)
{
    double s = 0.1 + 0.2;
    printf("0.1 + 0.2 = %.17g\n", s);
    printf("s == 0.3 gives %d\n", s == 0.3);
    printf("nearly_equal(s, 0.3) gives %d\n", nearly_equal(s, 0.3, 1e-12));
    char letter = 'A';
    printf("'A' is the integer %d, 'A' + 2 is '%c'\n", letter, letter + 2);
    return 0;
}
Listing 2.5. Rounding, a tolerant comparison, and characters as numbers code/bachelor-1/02-c-types-and-control/listings/floats.c
$ gcc -std=c17 -O2 -Wall -Wextra -o floats floats.c -lm && ./floats
0.1 + 0.2 = 0.30000000000000004
s == 0.3 gives 0
nearly_equal(s, 0.3) gives 1
'A' is the integer 65, 'A' + 2 is 'C'
Output 2.5. The sum differs from 0.30.3 in the seventeenth digit.

The last line shows that a char is a small integer: 'A' is the number 65, its code, and 'A' + 2 is 67, which %c prints as C. The type bool of <stdbool.h> holds 0 or 1, and in C every integer can be tested: zero is false, anything else is true.

2.3 Conversions and their traps

An arithmetic operator of C works on two operands of one type. When the types differ, or are narrower than int, the compiler converts them first, silently, by fixed rules.

Definition 2.3 (Integer promotion, usual arithmetic conversions)

The integer promotion converts an operand of a type narrower than int (char, short, their unsigned forms, bool) to int, since int can represent all their values. The usual arithmetic conversions then bring both operands of a binary operator to a common type: if either is floating, to the wider floating type. Otherwise, after promotion, with the ranks int << long << long long: (i) if both operands are signed or both unsigned, to the integer type of greater rank; (ii) if the unsigned operand has a rank greater than or equal to the other’s, to its unsigned type; (iii) if the signed operand has the greater rank, to that signed type when it can represent every value of the unsigned one, and otherwise to the unsigned type of the same rank. A signed operand converted to an unsigned type of width NN takes its value modulo 2N2^N.

Definition 2.4 (Cast)

A cast is an explicit conversion, written (type)expression. Converting a floating value to an integer type drops the fractional part (it truncates toward zero); converting an integer to a narrower unsigned type keeps it modulo 2N2^N.

#include <stdio.h>

int main(void)
{
    int minus_one = -1;
    unsigned one = 1;
    if (minus_one < one)
        puts("-1 < 1u is true");
    else
        puts("-1 < 1u is false");
    long big = -1;
    printf("-1L < 1u gives %d\n", big < one);
    unsigned char c = 300;               // 300 mod 256
    int i = 3.99;                        // the fraction is dropped
    int j = -3.99;
    printf("unsigned char 300 holds %d, (int)3.99 = %d, (int)-3.99 = %d\n", c, i, j);
    return 0;
Listing 2.6. Mixed signs and truncation code/bachelor-1/02-c-types-and-control/listings/conversions.c
$ gcc -std=c17 -O2 -Wall -Wextra -o conversions conversions.c -lm && ./conversions
conversions.c: In function 'main':
conversions.c:8:19: warning: comparison of integer expressions of different signedness: 'int' and 'unsigned int' [-Wsign-compare]
    8 |     if (minus_one < one)
      |                   ^
conversions.c:14:23: warning: unsigned conversion from 'int' to 'unsigned char' changes value from '300' to '44' [-Woverflow]
   14 |     unsigned char c = 300;               // 300 mod 256
      |                       ^~~
-1 < 1u is false
-1L < 1u gives 1
unsigned char 300 holds 44, (int)3.99 = 3, (int)-3.99 = -3
Output 2.6. -1 < 1u is false, as the warning foresaw.

Example 2.5 (Why -1 < 1u is false)

In minus_one < one, both operands have rank int and one is unsigned, so by case (ii) minus_one is converted to unsigned: −1 mod 232=4294967295-1 \bmod 2^{32} = 4294967295, which is not less than 1. In big < one, big is a long, of greater rank, and on this machine long can hold every unsigned value: by case (iii) one is converted to long, and −1<1-1 < 1 is true. The same expression gives the opposite answer on a system where long has 32 bits: long then cannot hold 4294967295, so case (iii) sends both operands to unsigned long, and big becomes 4294967295 again.

Where the usual arithmetic conversions lead two operands. Narrow types are first promoted to int. Two signed or two unsigned operands meet at the greater rank, up their column (i). A signed operand goes to the unsigned operand’s type when that rank is equal or greater: right at the same rank, then up (ii). When the signed operand has the greater rank, the unsigned one moves to it along a dashed arrow if that type holds all its values, as unsigned into a 64-bit long; if not, both go to the unsigned type of the greater rank (iii). A floating operand makes the whole operation floating.
Where the usual arithmetic conversions lead two operands. Narrow types are first promoted to int. Two signed or two unsigned operands meet at the greater rank, up their column (i). A signed operand goes to the unsigned operand’s type when that rank is equal or greater: right at the same rank, then up (ii). When the signed operand has the greater rank, the unsigned one moves to it along a dashed arrow if that type holds all its values, as unsigned into a 64-bit long; if not, both go to the unsigned type of the greater rank (iii). A floating operand makes the whole operation floating.

C converts without asking because it trusts the programmer; Python refuses "3" + 4 at run time, C would accept a pointer added to a character. This is what is meant by C’s weak typing: the compiler checks declarations but not the meaning of conversions. The warnings -Wsign-compare and -Woverflow of -Wall -Wextra catch the commonest cases, as above.

2.4 Operators and order of evaluation

Every expression of C is a tree: each operator is a node whose children are its operands, and the grammar’s precedence and associativity decide the shape. Three of the rules surprise, as the program below shows: shifts bind more loosely than +, the bitwise & more loosely than ==, and the logical operators evaluate their right operand only when they must.

#include <stdio.h>

int main(void)
{
    int x = 6;
    printf("1 << 2 + 1   = %d\n", 1 << 2 + 1);   // + binds tighter than <<
    printf("x & 1 == 0   = %d\n", x & 1 == 0);   // == binds tighter than &
    printf("(x & 1) == 0 = %d\n", (x & 1) == 0);
    int n = 0;
    if (n != 0 && 10 / n > 1)                     // && stops before dividing
        puts("never printed");
    printf("short-circuit kept us from dividing by %d\n", n);
    return 0;
}
Listing 2.7. Three expressions that group unexpectedly code/bachelor-1/02-c-types-and-control/listings/precedence.c
$ gcc -std=c17 -O2 -Wall -Wextra -o precedence precedence.c -lm && ./precedence
precedence.c: In function 'main':
precedence.c:7:37: warning: suggest parentheses around '+' inside '<<' [-Wparentheses]
    7 |     printf("1 << 2 + 1   = %d\n", 1 << 2 + 1);   // + binds tighter than <<
      |                                     ^~
precedence.c:8:37: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses]
    8 |     printf("x & 1 == 0   = %d\n", x & 1 == 0);   // == binds tighter than &
      |                                     ^
1 << 2 + 1   = 8
x & 1 == 0   = 0
(x & 1) == 0 = 1
short-circuit kept us from dividing by 0
Output 2.7. The compiler suggests the parentheses.

Definition 2.6 (Short-circuit evaluation)

In a && b and a || b, the operand a is evaluated first; b is evaluated only when a does not already decide the result (a true for &&, false for ||). This is short-circuit evaluation. A test such as n != 0 && 10 / n > 1 relies on it to avoid dividing by zero.

The tree of a + b * c > d && e != 0: * binds tighter than +, which binds tighter than >, and && is loosest. The left subtree of && is evaluated first, and the right one only if the left is true.
The tree of a + b * c > d && e != 0: * binds tighter than +, which binds tighter than >, and && is loosest. The left subtree of && is evaluated first, and the right one only if the left is true.

Integer division also has a rule worth stating: since C99, a / b truncates toward zero, and % is defined so that (a / b) * b + a % b == a; the remainder therefore takes the sign of a.

#include <stdio.h>

int main(void)
{
    int a[] = {7, -7, 7, -7};
    int b[] = {2, 2, -2, -2};
    for (int k = 0; k < 4; k++)
        printf("%2d / %2d = %2d   %2d %% %2d = %2d\n", a[k], b[k], a[k] / b[k], a[k], b[k],
               a[k] % b[k]);
    return 0;
}
Listing 2.8. Four divisions code/bachelor-1/02-c-types-and-control/listings/division.c
$ gcc -std=c17 -O2 -Wall -Wextra -o division division.c -lm && ./division
 7 /  2 =  3    7 %  2 =  1
-7 /  2 = -3   -7 %  2 = -1
 7 / -2 = -3    7 % -2 =  1
-7 / -2 =  3   -7 % -2 = -1
Output 2.8. Truncation toward zero: −7/2=−3-7/2 = -3, and −7 mod 2-7 \bmod 2 prints as −1-1.

Definition 2.7 (Side effect, sequencing)

A side effect of an expression is a change of state that its evaluation causes: storing into a variable (=, ++, +=), writing to a file. C fixes the order of side effects only at sequence points: the end of a full expression, the &&, || and comma operators, and a function call. Between two of them, two side effects on the same object, or a side effect and an unrelated read of the same object, make the behaviour undefined.

#include <stdio.h>

int main(void)
{
    int i = 1;
    i = i++ + 1;                         // undefined behaviour
    printf("i = %d\n", i);
    return 0;
}
Listing 2.9. Two writes to i with no order code/bachelor-1/02-c-types-and-control/listings/sequence.c
$ gcc -std=c17 -O2 -Wall -Wextra -o sequence sequence.c -lm && ./sequence
sequence.c: In function 'main':
sequence.c:7:7: warning: operation on 'i' may be undefined [-Wsequence-point]
    7 |     i = i++ + 1;                         // undefined behaviour
      |     ~~^~~~~~~~~
i = 2
Output 2.9. The compiler warns; the printed 2 means nothing.

The variable i is written by ++ and by =, in no fixed order: is the result 2, or 3? Neither is promised, and another compiler may print the other. Keep each side effect in its own statement. The qualifier const, finally, declares an object that the program will not modify: const int days = 7; is checked by the compiler, which refuses an assignment to days.

2.5 Control flow and undefined behaviour

C’s statements for control flow are those of Python with different spelling: if/else, while, for (init; test; step), break and continue, plus do { } while (test);, which tests after the body and so runs it at least once. One statement has no Python twin.

Definition 2.8 (Switch statement, fall-through)

A switch statement, written with switch, evaluates an integer expression and jumps to the case label with that value, or to default. Execution then continues downwards through the following labels until a break: passing from one case into the next is called fall-through.

#include <stdio.h>

int days_in(int month)
{
    int days = 0;
    switch (month) {
    case 2:
        days = 28;
        break;
    case 4: case 6: case 9: case 11:
        days = 30;
    default:
        days = 31;
    }
    return days;
}

int main(void)
{
    printf("February %d, April %d, May %d\n", days_in(2), days_in(4), days_in(5));
    return 0;
}
Listing 2.10. A missing break code/bachelor-1/02-c-types-and-control/listings/days.c
$ gcc -std=c17 -O2 -Wall -Wextra -o days days.c -lm && ./days
days.c: In function 'days_in':
days.c:12:14: warning: this statement may fall through [-Wimplicit-fallthrough=]
   12 |         days = 30;
      |         ~~~~~^~~~
days.c:13:5: note: here
   13 |     default:
      |     ^~~~~~~
February 28, April 31, May 31
Output 2.10. April has 31 days, says the program.

The warning names the statement that falls through. A deliberate fall-through is marked with a comment /* fall through */, which also silences the warning (Exercise 2.8 uses one).

The switch of days_in as jumps. The value of month selects an entry point; without a break the thirty-day case runs on into default, which overwrites 30 with 31.
The switch of days_in as jumps. The value of month selects an entry point; without a break the thirty-day case runs on into default, which overwrites 30 with 31.

The countdown of the opening, and the signed overflow of Listing 2.4, show that some programs are legal C and still have no meaning. The standard sorts such situations into three kinds.

Definition 2.9 (Undefined, unspecified, implementation-defined behaviour)

Undefined behaviour is the behaviour of a construct for which the standard imposes no requirement at all: signed overflow, an access outside an array, two unsequenced side effects on one object, use of an uninitialised variable. Unspecified behaviour allows several outcomes without saying which: the order in which the two operands of + are evaluated. Implementation-defined behaviour is unspecified behaviour that each implementation must document: the width of int, or whether char is signed.

Undefined behaviour is not “the processor does something odd”. Because a correct program never contains it, the compiler is allowed to assume that it never happens, and optimises on that assumption. The function below asks whether x + 1 > x. For a mathematical integer the answer is always yes, and since signed overflow cannot happen in a valid program, the compiler replaces the comparison by 1.

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int bigger_after_increment(int x)
{
    return x + 1 > x;
}

int main(int argc, char **argv)
{
    int x = argc > 1 ? atoi(argv[1]) : INT_MAX;
    printf("x + 1 > x for x = %d gives %d\n", x, bigger_after_increment(x));
    return 0;
}
Listing 2.11. A test that the compiler answers in advance code/bachelor-1/02-c-types-and-control/listings/fold.c
$ gcc -std=c17 -O2 fold.c -o fold
$ ./fold
x + 1 > x for x = 2147483647 gives 1
$ gcc -std=c17 -O2 -fwrapv fold.c -o fold_wrap
$ ./fold_wrap
x + 1 > x for x = 2147483647 gives 0
Output 2.11. With the standard rules the answer is 1, even for x=231−1x = 2^{31}-1; with -fwrapv, a dialect where signed arithmetic wraps, it is 0.

The wrapped value x+1=−231x + 1 = -2^{31} is smaller than xx, so a program that wants to detect overflow by testing the result after the fact is wrong twice: the overflow has already happened, and the test may have been removed. Overflow must be prevented by testing the operands before the operation, as Exercises 2.7 and 2.11 do.

Safe use

Build every program while developing with -Wall -Wextra and, for tests, with -fsanitize=undefined (and, from Chapter 4, -fsanitize=address). The sanitizers report the undefined behaviour that a run actually meets; they cannot prove that a program has none.

2.6 Exercises

Exercise 2.1 ★

Predict the four numbers printed by the program below.

#include <stdio.h>

int main(void)
{
    unsigned char a = (unsigned char)300;
    signed char b = (signed char)200;
    int c = (int)7.99;
    int d = (int)-7.99;
    printf("%d %d %d %d\n", a, b, c, d);
    return 0;
}
Listing 2.12. Four conversions code/bachelor-1/02-c-types-and-control/listings/casts.c
Solution

Solution of Exercise 2.1.

300 mod 256=44300 \bmod 256 = 44; the pattern of 200 read as a signed 8-bit number is 200−256=−56200 - 256 = -56 (implementation-defined, two’s complement here); 7.997.99 and −7.99-7.99 truncate toward zero.

$ gcc -std=c17 -O2 -Wall -Wextra -o casts casts.c -lm && ./casts
44 -56 7 -7
Output 2.14. The four conversions.

Exercise 2.2 ★

Predict -9 / 4, -9 % 4, 9 / -4 and 9 % -4 in C, and check each pair against the identity (a / b) * b + a % b == a. What does Python print for the same four, and why does it differ?

Solution

Solution of Exercise 2.2.

C truncates toward zero: −9/4=−2-9/4 = -2 and −9 % 4=−1-9 \,\%\, 4 = -1 (indeed (−2)⋅4−1=−9(-2)\cdot 4 - 1 = -9); 9/−4=−29/{-4} = -2 and 9 % −4=19 \,\%\, {-4} = 1 ((−2)(−4)+1=9(-2)(-4) + 1 = 9).

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_div exo_div.c -lm && ./exo_div
-2 -1 -2 1
Output 2.15. The C results.

Python’s // rounds down (toward −∞-\infty) and its % takes the sign of the divisor: −9 // 4=−3-9 \,//\, 4 = -3, −9 % 4=3-9 \,\%\, 4 = 3, 9 // −4=−39 \,//\, {-4} = -3, 9 % −4=−39 \,\%\, {-4} = -3. Both languages keep the identity; they choose different quotients.

Exercise 2.3 ★

Predict the four values (0 or 1) printed by the program below, naming the conversion that decides each.

#include <stdio.h>

int main(void)
{
    unsigned char big = 200;
    signed char neg = -1;
    unsigned u = 0;
    long l = -1;
    printf("%d %d %d %d\n", -1 < (int)u, l < 1u, big < neg, (unsigned)neg > 1000u);
    return 0;
}
Listing 2.13. Four mixed comparisons code/bachelor-1/02-c-types-and-control/listings/exo_compare.c
Solution

Solution of Exercise 2.3.

-1 < (int)u: both int, −1<0-1 < 0, so 1. l < 1u: long has greater rank and holds every unsigned, so 1u becomes long: 1. big < neg: both promoted to int, 200<−1200 < -1 is false: 0. (unsigned)neg > 1000u: −1-1 becomes 4294967295: 1.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_compare exo_compare.c -lm && ./exo_compare
1 1 0 1
Output 2.16. The four comparisons.

Exercise 2.4 ★

Trace the program below and predict its line of output.

#include <stdio.h>

int main(void)
{
    int n = 20, steps = 0;
    do {
        n -= 7;
        steps++;
    } while (n > 0);
    int m = -1, turns = 0;
    while (m > 0) {
        m -= 7;
        turns++;
    }
    printf("n = %d after %d steps; m = %d after %d turns\n", n, steps, m, turns);
    return 0;
}
Listing 2.14. A do–while and a while code/bachelor-1/02-c-types-and-control/listings/exo_dowhile.c
Solution

Solution of Exercise 2.4.

The do body runs before the first test: nn goes 20→13→6→−120 \to 13 \to 6 \to -1 in 3 steps. The while loop tests first, −1>0-1 > 0 is false, so it runs 0 times.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_dowhile exo_dowhile.c -lm && ./exo_dowhile
n = -1 after 3 steps; m = -1 after 0 turns
Output 2.17. The trace’s result.

Exercise 2.5 ★★

The average of the marks 12, 15, 9 and 14 is 12.5, yet the program prints 12.00. Find the bug and fix it with one cast.

#include <stdio.h>

int main(void)
{
    int marks[] = {12, 15, 9, 14};
    int sum = 0;
    for (int i = 0; i < 4; i++)
        sum += marks[i];
    double average = sum / 4;
    printf("average = %.2f\n", average);
    return 0;
}
Listing 2.15. An average that loses its half code/bachelor-1/02-c-types-and-control/listings/average.c
Solution

Solution of Exercise 2.5.

sum / 4 divides two ints, which truncates: 50/4=1250 / 4 = 12; only then is the result converted to double. Converting one operand first makes the division floating: double average = (double)sum / 4; prints average = 12.50.

$ gcc -std=c17 -O2 -Wall -Wextra -o average average.c -lm && ./average
average = 12.00
Output 2.18. Before the fix.

Exercise 2.6 ★★

A binary search computes the middle of two indices with the function middle below. Read the sanitizer’s report, explain the printed value, and rewrite middle so that it cannot overflow when 0≤lo≤hi0 \leq lo \leq hi.

#include <stdio.h>

int middle(int lo, int hi)
{
    return (lo + hi) / 2;
}

int main(void)
{
    printf("middle(10, 20) = %d\n", middle(10, 20));
    printf("middle(2000000000, 2100000000) = %d\n", middle(2000000000, 2100000000));
    return 0;
}
Listing 2.16. The middle of two indices code/bachelor-1/02-c-types-and-control/listings/midpoint.c
$ gcc -std=c17 -O0 -fsanitize=undefined -o midpoint midpoint.c -lm && ./midpoint
midpoint.c:7:16: runtime error: signed integer overflow: 2000000000 + 2100000000 cannot be represented in type 'int'
middle(10, 20) = 15
middle(2000000000, 2100000000) = -97483648
Output 2.12. Built with the sanitizer. The report comes first: standard output is held in a buffer until the program ends, its errors are not.
Solution

Solution of Exercise 2.6.

2 000 000 000+2 100 000 000=4 100 000 000>231−12\,000\,000\,000 + 2\,100\,000\,000 = 4\,100\,000\,000 > 2^{31} - 1: the sum overflows. On this machine it wrapped to 4 100 000 000−232=−194 967 2964\,100\,000\,000 - 2^{32} = -194\,967\,296, halved to −97 483 648-97\,483\,648. Write return lo + (hi - lo) / 2;: with 0≤lo≤hi0 \leq lo \leq hi, hi−lohi - lo lies in [0,hi][0, hi], and lo+(hi−lo)/2≤hilo + (hi-lo)/2 \leq hi, so no step leaves the range of int.

Exercise 2.7 ★★

Write int32_t sat_add(int32_t a, int32_t b), which returns a+ba + b when it fits in int32_t, INT32_MAX when the sum is larger and INT32_MIN when it is smaller, without ever computing an overflowing sum.

Solution

Solution of Exercise 2.7.

Test the operands before adding: if b>0b > 0, the sum exceeds INT32_MAX exactly when a>INT32_MAX−ba > \texttt{INT32\_MAX} - b, and that subtraction cannot overflow because b>0b > 0; symmetrically for b<0b < 0. The tested solution is exercises/sat_add.c (test tests/sat_add_test.c):

int32_t sat_add(int32_t a, int32_t b)
{
    if (b > 0 && a > INT32_MAX - b)
        return INT32_MAX;
    if (b < 0 && a < INT32_MIN - b)
        return INT32_MIN;
    return a + b;
}
Saturating addition code/bachelor-1/02-c-types-and-control/exercises/sat_add.c

Exercise 2.8 ★★

Predict the three lines printed by this program, whose fall-throughs are deliberate.

#include <stdio.h>

int main(void)
{
    for (int level = 1; level <= 3; level++) {
        int score = 0;
        switch (level) {
        case 1:
            score += 100;
            /* fall through */
        case 2:
            score += 10;
            /* fall through */
        case 3:
            score += 1;
        }
        printf("level %d: %d\n", level, score);
    }
    return 0;
}
Listing 2.17. Deliberate fall-through code/bachelor-1/02-c-types-and-control/listings/exo_switch.c
Solution

Solution of Exercise 2.8.

Level 1 enters at case 1 and falls through all three: 100+10+1100 + 10 + 1. Level 2 enters at case 2: 11. Level 3: 1.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_switch exo_switch.c -lm && ./exo_switch
level 1: 111
level 2: 11
level 3: 1
Output 2.19. The three scores.

Exercise 2.9 ★★

Count the values x of type uint8_t for which (uint8_t)(x * x) == 1, and prove your count. (Hint: x2−1=(x−1)(x+1)x^2 - 1 = (x-1)(x+1).)

Solution

Solution of Exercise 2.9.

Four values: 1, 127, 129 and 255. Proof: we need x2≡1(mod256)x^2 \equiv 1 \pmod{256}, that is 256∣(x−1)(x+1)256 \mid (x-1)(x+1). Then xx is odd, so x−1x - 1 and x+1x + 1 are two consecutive even numbers; one of them is ≡2(mod4)\equiv 2 \pmod 4 and carries a single factor 2, so the other carries at least seven: x≡1x \equiv 1 or x≡−1(mod128)x \equiv -1 \pmod{128}. In [0,255][0, 255] that gives x∈{1,129}x \in \{1, 129\} or x∈{127,255}x \in \{127, 255\}, and each works (for instance 1272=16129=63⋅256+1127^2 = 16129 = 63 \cdot 256 + 1). The chapter’s test tests/test_squares_mod.py checks the count by brute force.

Exercise 2.10 ★★★

Let x be an unsigned integer of width NN. Prove that x + (~x + 1) is 0, where ~ flips every bit. Deduce why, in two’s complement, negating a number is “flip the bits and add one”.

Solution

Solution of Exercise 2.10.

Each bit of ~x is 11 minus the bit of xx, so x+~xx + \texttt{\textasciitilde x} has every bit set: it equals 2N−12^N - 1. Hence x+(~x+1)=2N≡0(mod2N)x + (\texttt{\textasciitilde x} + 1) = 2^N \equiv 0 \pmod{2^N}. In two’s complement, −x-x is represented by 2N−x2^N - x, which we have just shown equals ~x+1\texttt{\textasciitilde x} + 1: negation is “flip the bits and add one”.

Exercise 2.11 ★★★

Write bool mul_overflows(int64_t a, int64_t b), true exactly when the product abab is outside the range of int64_t, using only comparisons and divisions that cannot themselves overflow. Justify each case.

Solution

Solution of Exercise 2.11.

If either factor is 0 there is no overflow. Otherwise compare one factor with a quotient that is always representable: both positive, overflow iff a>INT64_MAX/ba > \texttt{INT64\_MAX} / b; a>0>ba > 0 > b, iff b<INT64_MIN/ab < \texttt{INT64\_MIN} / a; a<0<ba < 0 < b, iff a<INT64_MIN/ba < \texttt{INT64\_MIN} / b; both negative (positive product), iff a<INT64_MAX/ba < \texttt{INT64\_MAX} / b. Each division has a divisor that is not 0 and never divides INT64_MIN by −1-1. The tested solution compares with the compiler’s checked multiplication on a table of extreme values:

bool mul_overflows(int64_t a, int64_t b)
{
    if (a == 0 || b == 0)
        return false;
    if (a > 0) {
        if (b > 0)
            return a > INT64_MAX / b;    // both positive
        return b < INT64_MIN / a;        // a > 0, b < 0
    }
    if (b > 0)
        return a < INT64_MIN / b;        // a < 0, b > 0
    return a < INT64_MAX / b;            // both negative: a * b > 0
}
Testing the factors first code/bachelor-1/02-c-types-and-control/exercises/mul_overflows.c

Exercise 2.12 ★★★

With long long total = 0;, for which values of n (an int) does the loop for (int i = 0; i <= n; i += 2) total += i; have undefined behaviour? Prove your answer, then give a version that is correct for every n.

Solution

Solution of Exercise 2.12.

The body runs for the even ii with 0≤i≤n0 \leq i \leq n; after the body with i=2ki = 2k, the loop computes 2k+22k + 2, which overflows exactly when 2k+2>INT_MAX=231−12k + 2 > \texttt{INT\_MAX} = 2^{31} - 1, that is when 2k=231−22k = 2^{31} - 2, the largest even int. That body runs iff n≥231−2n \geq 2^{31} - 2. So the behaviour is undefined exactly for n=231−2n = 2^{31} - 2 and n=231−1n = 2^{31} - 1, and defined for every other n (for n<0n < 0 the loop does not run). The sum itself is safe: it is at most 2+4+⋯+(231−2)<2602 + 4 + \dots + (2^{31} - 2) < 2^{60}, far below the largest long long; with an int total it would overflow from n=92 682n = 92\,682 on, since 2+4+⋯+2m=m(m+1)2 + 4 + \dots + 2m = m(m + 1) exceeds 231−12^{31} - 1 from m=46 341m = 46\,341. A correct version counts in a wider type: for (long long i = 0; i <= n; i += 2); or it stops before stepping: if (i > n - 2) break; at the end of the body, where n−2n - 2 cannot overflow because n≥0n \geq 0 there.

2.7 Problem: A checksum that works by luck

Problem 2.1

Weekend problem — A checksum that works by luck

The weather service of Brenmoor stores each daily temperature, in tenths of a degree, as a 16-bit two’s complement number tit_i. To check that a copy of the file is intact, it computes the checksum

C=(∑i=0n−2wi wi+1) mod 232,C = \Bigl(\sum_{i=0}^{n-2} w_i \, w_{i+1}\Bigr) \bmod 2^{32},

where wi∈[0,216)w_i \in [0, 2^{16}) is the 16-bit pattern of tit_i read as an unsigned number. Colleague A wrote checksum_naive.c; colleague B, worried by a compiler warning on another project, wrote checksum_fixed.c; a Python version serves as the specification.

uint32_t checksum(const uint16_t *w, int n)
{
    uint32_t s = 0;
    for (int i = 0; i + 1 < n; i++)
        s += w[i] * w[i + 1];            // both operands promoted to int
    return s;
}
Listing 2.18. Colleague A’s loop code/bachelor-1/02-c-types-and-control/listings/checksum_naive.c
uint32_t checksum(const uint16_t *w, int n)
{
    uint32_t s = 0;
    for (int i = 0; i + 1 < n; i++)
        s += (uint32_t)w[i] * w[i + 1];  // unsigned product: wraps, never overflows
    return s;
}
Listing 2.19. Colleague B’s loop code/bachelor-1/02-c-types-and-control/listings/checksum_fixed.c
$ gcc -std=c17 -O2 -Wall -Wextra checksum_naive.c temps.c -lm -o naive
$ ./naive weather.csv
731 readings, checksum 73402730
$ gcc -std=c17 -O0 -fsanitize=undefined checksum_naive.c temps.c -lm -o naive_ub
$ ./naive_ub weather.csv
checksum_naive.c:10:19: runtime error: signed integer overflow: 65535 * 65533 cannot be represented in type 'int'
731 readings, checksum 73402730
$ gcc -std=c17 -O2 -Wall -Wextra checksum_fixed.c temps.c -lm -o fixed
$ ./fixed weather.csv
731 readings, checksum 73402730
$ python3 checksum_ref.py weather.csv
731 readings, checksum 73402730
2 of 730 products exceed INT_MAX
largest word 65535
Output 2.13. The four computations.

Part I — Widths and the specification.

  1. What is the range of tit_i, and how many tenths of a degree does it allow? Is it enough for a town’s weather?
  2. Give wiw_i for ti=25t_i = 25 (2.5 degrees), ti=−1t_i = -1 and ti=−990t_i = -990 (the error code −99.0-99.0).
  3. Show that wi=ti mod 216w_i = t_i \bmod 2^{16} for every tit_i in the range of int16_t.
  4. What is the largest possible value of one product wiwi+1w_i w_{i+1}? How many bits does it need?
  5. How many bits does the exact sum ∑wiwi+1\sum w_i w_{i+1} need, at most, for n=731n = 731?

Part II — Arithmetic modulo 2322^{32}.

  1. Prove that (a+b) mod m=((a mod m)+(b mod m)) mod m(a + b) \bmod m = \bigl((a \bmod m) + (b \bmod m)\bigr) \bmod m for natural numbers aa, bb and m≥1m \geq 1.
  2. Deduce that adding the products one by one into a uint32_t computes CC exactly, provided each product itself is computed exactly or modulo 2322^{32}.
  3. Prove the same law for products: (ab) mod m=((a mod m)(b mod m)) mod m(ab) \bmod m = \bigl((a \bmod m)(b \bmod m)\bigr) \bmod m.
  4. Why does colleague B’s cast (uint32_t)w[i] make the whole product unsigned, and what range of results can it produce?
  5. Could B use uint16_t for the cast instead? Explain.

Part III — The promotion trap.

  1. In A’s loop, what type do w[i] and w[i + 1] have when they are multiplied, and why?
  2. Show that wiwi+1w_i w_{i+1} overflows that type exactly when wiwi+1>231−1w_i w_{i+1} > 2^{31} - 1.
  3. Find the smallest aa such that a⋅aa \cdot a overflows int. (Compute 46340246340^2 and 46341246341^2.)
  4. Which temperatures tit_i give wi≥46341w_i \geq 46341? For readings of at least −1919.5-1919.5 degrees, as every real one is, conclude that a product overflows exactly when both of its readings are negative.
  5. The sanitizer reported 65535×6553365535 \times 65533. Which two consecutive readings were they?
  6. The Python specification counted 2 products above INT_MAX among 730. The second involves readings of −2.3-2.3 and −0.9-0.9 degrees. Give its two words and check that their product exceeds 231−12^{31} - 1.
  7. Over all pairs (a,b)∈[0,216)2(a, b) \in [0, 2^{16})^2, the number of products above 231−12^{31}-1 is 658 928 599. What fraction of all pairs is it, roughly?

Part IV — Luck, and the fix.

  1. All four computations printed 73 402 730. Explain why A’s program printed the right value on this machine, although its behaviour is undefined.
  2. Using Output 2.11, describe how a compiler could legally make A’s program print something else.
  3. Why did the warnings of -Wall -Wextra not catch A’s bug, while the sanitizer did?
  4. Why did the sanitizer report only one of the two overflowing products?
  5. Rewrite A’s loop with uint64_t instead of uint32_t, and say whether the result can differ.
  6. What is CC printed in hexadecimal? (Divide by 65536 to get the upper half.)
  7. State the named result of the problem: the condition under which a product of two uint16_t is undefined in C, the smallest equal operands, and what the data gave.
Solution

Solution of Problem 2.1.

1. ti∈[−32768,32767]t_i \in [-32768, 32767], from −3276.8-3276.8 to 3276.73276.7 degrees: far more than any weather needs.

2. w=25w = 25; w=65535w = 65535; w=65536−990=64546w = 65536 - 990 = 64546.

3. For t≥0t \geq 0 the bits read the same in both ways: w=t=t mod 216w = t = t \bmod 2^{16}. For t<0t < 0 the two’s complement pattern of tt is that of 216+t∈[215,216)2^{16} + t \in [2^{15}, 2^{16}), which is t mod 216t \bmod 2^{16}.

4. 655352=4 294 836 225<23265535^2 = 4\,294\,836\,225 < 2^{32}: 32 bits.

5. 730 products, each below 2322^{32}: the sum is below 730⋅232<210⋅232730 \cdot 2^{32} < 2^{10} \cdot 2^{32}, so 42 bits.

6. Write a=qm+ra = qm + r and b=q′m+r′b = q'm + r' with 0≤r,r′<m0 \leq r, r' < m. Then a+b=(q+q′)m+(r+r′)a + b = (q + q')m + (r + r'), so a+ba + b and r+r′r + r' have the same remainder modulo mm.

7. By induction on the loop: if ss holds the partial sum modulo 2322^{32} and the product pp is exact or reduced modulo 2322^{32}, the unsigned addition stores (s+p) mod 232(s + p) \bmod 2^{32}, which by question 6 is the next partial sum modulo 2322^{32}.

8. ab=(qm+r)(q′m+r′)=m(qq′m+qr′+q′r)+rr′ab = (qm + r)(q'm + r') = m(qq'm + qr' + q'r) + rr', so ab≡rr′(modm)ab \equiv rr' \pmod m.

9. (uint32_t)w[i] has type unsigned int, of rank int; by the usual arithmetic conversions the promoted w[i + 1] becomes unsigned int too, and the product is computed modulo 2322^{32}, in [0,232)[0, 2^{32}). Since the exact product is below 2322^{32} (question 4), it is even exact.

10. No: a uint16_t operand is promoted to int again, and the trap returns.

11. Both are uint16_t, narrower than int; the integer promotion converts them to int, which can hold every value from 0 to 65535.

12. The exact product is a natural number; it is representable in int iff it is at most 231−12^{31} - 1.

13. 463402=2 147 395 600≤2 147 483 647<463412=2 147 488 28146340^2 = 2\,147\,395\,600 \leq 2\,147\,483\,647 < 46341^2 = 2\,147\,488\,281: the smallest is a=46341a = 46341.

14. w≥46341w \geq 46341 iff t<0t < 0 and t+65536≥46341t + 65536 \geq 46341, that is −19195≤t≤−1-19195 \leq t \leq -1, in tenths of a degree: with readings of at least −1919.5-1919.5 degrees, every negative reading. (Without that bound the claim fails: t=−25536t = -25536 gives w=40000w = 40000, and 40000×6553540000 \times 65535 overflows.) A non-negative reading has w≤32767w \leq 32767 and 32767⋅65535=2 147 385 345≤231−132767 \cdot 65535 = 2\,147\,385\,345 \leq 2^{31} - 1, so it never overflows; and two readings in [−19195,−1][-19195, -1] give a product at least 46341246341^2. So a product overflows exactly when two consecutive readings are both negative.

15. 6553565535 is −1-1 (−0.1-0.1 degree) and 6553365533 is −3-3 (−0.3-0.3 degree): the Riverside reading of 22 January and the Hilltop reading of 23 January.

16. −23↦65513-23 \mapsto 65513 and −9↦65527-9 \mapsto 65527; 65513⋅65527=4 292 870 351>231−165513 \cdot 65527 = 4\,292\,870\,351 > 2^{31} - 1.

17. 658 928 599/232≈0.153658\,928\,599 / 2^{32} \approx 0.153: about 15 % of all pairs.

18. The processor’s multiplication keeps the low 32 bits; the negative int it produced was then converted to uint32_t for the addition, which gives back exactly the low 32 bits of the true product. The result is right because this compiler, at these options, happened to emit that instruction.

19. The compiler may assume that w[i] * w[i + 1] never exceeds INT_MAX, as it assumed x + 1 > x: for instance it may compute the product in a narrower or a reordered way, or delete a later test that only an overflow could make true. Any output is then legal.

20. A warning is decided when compiling, without the data; the multiplication is valid for most values. The sanitizer checks the values actually met at run time.

21. The sanitizer reports each source location once by default; both overflows happen at the same line and column.

22. uint64_t s = 0; s += (uint64_t)w[i] * w[i + 1]; then return (uint32_t)s: the same CC, since reducing at the end or at each step gives the same remainder (question 6). Without the cast on the product, the promotion to int still happens first, and the trap remains.

23. 73 402 730=1120⋅65536+241073\,402\,730 = 1120 \cdot 65536 + 2410, and 1120=0x4601120 = \texttt{0x460}, 2410=0x96A2410 = \texttt{0x96A}: 0x0460096A.

24. The promotion trap. A product of two uint16_t is computed in int and is undefined exactly when ab>231−1ab > 2^{31} - 1; the smallest equal operands are 4634146341, and about 15 % of all pairs overflow. In the town’s 731 readings, 2 of the 730 products did; all four programs printed C=73 402 730C = 73\,402\,730, but only colleague B’s version is guaranteed to.

Termos definidos neste capítulo

Ver todos os 1050 termos do glossário