Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Reading

(1-2h) Study Chapter 10 including exercise 10.4 (p. 570) with the learning goals in mind. The following section/s is/are optional:

In the following you also find my own notes.

Learning goals

10.1 Introduction

10.2 Structure Definition

(Person &) @0x7cada7114000
(unsigned long) 0

Remember lines and line_count in Exercise 5, which described an array that tracks its runtime size. Now we can marry them 🧑‍🤝‍🧑 and pass them as a single parameter to a function.

Person and WordList are called tags.

Self-referential structures

(char[50]) "Totoro"

Used to build linked lists.

Defining struct variables

Similar to other datatypes:

(Person &) @0x7cada710816c

Tagged or untagged

(unsigned long) 0

Tagged struct. We can use the tag to introduce other variables. Recommended.

(unsigned long) 0

Untagged struct — if we are sure we are not going to use it again.

Assignment

Structs do not decay to pointers like arrays, so we can do operations on the whole object.

person1:
Nature - 2147483648 - 10000.00
person2:
Totoro - 49 - 892.10
person2 now:
Nature - 2147483648 - 10000.00

Assignment copies whole object

(char[50]) "Nature"

an existing struct

(char[50]) ""

Assign to zero

/tmp/cell-tq43ywqc.repl:2:5: error: array type 'int[2]' is not assignable
    2 | arr = {}
      | ~~~ ^
error: Parsing failed.

With arrays this was not possible.

(char[50]) "Sima"

Assign to multiple values

/tmp/cell-0f3h469o.repl:1:1: error: use of undeclared identifier 'arr'
    1 | arr = {0, 1};
      | ^~~
error: Parsing failed.

With arrays this was also not possible

Other operations:

Comparison is not allowed

/tmp/cell-3_201kax.repl:1:9: error: invalid operands to binary expression
      ('struct Person2' and 'struct Person2')
    1 | person1 == person2
      | ~~~~~~~ ^  ~~~~~~~
error: Parsing failed.

We see that assignment is possible, but surprisingly not comparison. Why? On StackOverflow are some answers.

In short, C tries to keep things simple and efficient.

10.3 Initialization

Similar to arrays

(unsigned int) 255

10.4 Accessing members

  1. .

  2. -> (indirection and member access) because we often work with pointers to larger objects in C. Same as (*ptr).member

(unsigned int) 255
(unsigned int) 255

10.5 Using with functions

Wrap an array with a struct to pass it by value:

(int) 100

set_last_element gets a copy (pass by value), so it only modifies a copy of the struct (and array).

(int) 0

The array in the outer scope is not modified.

10.6 typedef

To create synonyms for other types. For example size_t is actually a typedef:

Searching for size_t in the header files of clang:

grep size_t "$(clang -print-resource-dir)/include/__stddef_size_t.h"

Outputs:

...
typedef __SIZE_TYPE__ size_t;

Searching for __SIZE_TYPE__ constant

echo | clang -dM -E - | grep __SIZE_TYPE__
#define __SIZE_TYPE__ long unsigned int
(Pixel2 &) @0x7cada6a2e000

Shorter than struct Pixel. We don’t need the tag name when we use typedef.

10.7 Random-number simulation case study

Now we can define a card structure and create a synonym with typedef:

First struct card and then typedef

Direct typedef with untagged struct

10.8 Union

Compared to struct, members of the union share the same memory:

a @ 0x7cada6a2a000
b @ 0x7cada6a2a008
a @ 0x7cada6a26000
b @ 0x7cada6a26000

Useful for data should be interpreted differently based on the scenario or has two different many of accessing the same data, see Figure 18.

For other examples: StackOverflow.

10.9 Bitwise operators

Often used to read-write to hardware registers, e.g., in a microcontroller like ATmega4808. Assume you want to set the direction of two pins as output using the Data Direction Set register:

PORTB.DIRSET = PIN0_bm | PIN1_bm;

PIN0_bm is 0x01, PIN1_bm 0x02 etc. Using |, we get ...0011.

Another example: to display the bits of an integer by shifting a 1 gradually using << and masking using & operator.

10.10 Bit fields

Used to pack data tighter.

(unsigned int) 0

We can also declare variables with exact number of bits: _BitInt() in C23 for exact bit amount specification

bitint.c
#include <stdio.h>
unsigned _BitInt(2) two_bits = 3uwb; // wb stands for _BitInt
int main() { printf("%u", (unsigned)++two_bits); }

3 + 1 should give 0 with only two bits.

bitint.transcript.txt
0

Indeed 0.

10.11 Enumeration constants

We can assign our own values

(Month1) (JAN1) : unsigned int 0

Without any explicit values

(Month2) (JAN2) : unsigned int 1

With explicit value/s

We can also set the data type:

(Month3) (JAN3) : char 1

With explicit value/s

10.12 Anonymous structures and unions

A C11 feature.

(S &) @0x7cada6a12000

Useful in unions and tagged unions

(double[3]) { 0.0, 0.0, 0.0 }

Figure 18:struct with x, y, z is anonymous. The struct and raw are alternative views to data

(double) 0.0

A tagged union that can read data as a string or float.

Credits: StackOverflow

10.13 Secure Programming

structs:

typedef:

bit manipulation

Binary literals

Not covered in the book.

Similar to octals and hexadecimals.

(int) 4

Printing:

100

Raylib

Installation

Windows amd64
MacOS
Windows arm64

You can follow the text instructions or/and screencast.

Screencast

Screencast of installation & running

Text instructions

  1. Go to the latest Raylib release.

  2. Scroll down to Assets:

  3. Under Assets, download the package raylib-*_win64_mingw-w64.zip

  4. Right-click the file, and click Extract All.

  5. Click Browse:

  6. Select your code folder. If you followed the Folder structure for the semester, the path should look similar to:

    Example path to your code folder.

    Example path to your code folder.

    Expected folder layout:

    ...
    📁 code
    ├── 📁 EXTRACTED-RAYLIB-FOLDER
    ├── 📁 repository1
    ├── 📁 repository2
    ├── 📁 ...
  7. Click Extract. The extracted folder will be shown.

  8. Rename the raylib-* folder to raylib, so you get the following layout:

    ...
    📁 code
    ├── 📁 raylib
    ├── 📁 repository1
    ├── 📁 repository2
    ├── 📁 ...

Running Raylib template

  1. Clone our Raylib template https://github.com/dtucprog/c-template-multi-raylib

  2. Click raylib_hello.c and run it using F5. You should see:

    Congratulations 💯

Appendix

Mimicking inheritance using structs

C does not support object-oriented programming and thus inheritance. First I thought we can do something similar with anonymous structures, because if an anonymous struct or union is added, then their items are appended at the same level. However the left example does not work and we have to provide a name to base a new struct on another tagged struct:

(char *) 0