ENG270 Introduction to C

Satoshi Takahama

EPFL

2024-10-09

Why C

Speed

USDA

NZZ


Eshel et al., doi:10.1007/s41781-023-00104-x, 2023

Memory

Topping et al., doi:10.3389/frsc.2021.786563, 2021

learn.epfl.ch


Fourment et al., doi:10.1186/1471-2105-9-82, 2008

Anatomy of a C program

Sum of natural numbers up to 10

sum = 1 + 2 + 3 + ... + 10

C code

#include <stdio.h>
int main() {
    int n, i, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (i = 1; i <= n; ++i) {
        sum += i;
    }

    printf("Sum = %d", sum);
    return 0;
}

Basic elements

  • #include statement to import libraries
  • main() function with return value of 0
  • required type annotations everywhere
  • semicolon is required at the end of each statement

Differences from Python and MATLAB

  • compiled
  • explicit memory management
    • let your compiler know how much memory to allocate based on variable types, array size, etc. (static typing)
    • static memory allocation - memory for variables that persist throughout program execution
    • dynamic memory allocation - memory for variables (arrays) created during program execution - must manually free up after use
    • don’t copy arrays but use pointers to location in memory

Compiler vs. Interpreter

C compiler

once program is compiled, can run on machine it was compiled for without user having to install C

Python interpreter

user needs to install Python to run Python scripts

realpython.com

Installation

  1. VSCode
  2. C/C++ extension in VSCode
  3. C compiler
    • Windows: GCC and GDB and tools installed through MSYS2
    • macOS: Clang/LLVM and LLDB (already installed or install with xcode)
    • GNU/Linux: use GCC and GDB

Windows instructions

macOS instructions

For Windows users - setting the proper terminal

Go to Command Palette and open Preferences: Open Users Settings (JSON).

Copy the relevant information below (not the text between /* */):

{
    /*
      Other stuff
    */
    "terminal.integrated.profiles.windows": {
        /*
          "PowerShell", "Command Prompt" profiles
        */
        "MSYS2_UCRT64": {
            "path": "C:\\msys64\\usr\\bin\\bash.exe",
            "args": [
                "--login",
                "-i"
            ],
            "env": {
                "MSYSTEM": "UCRT64",
                "CHERE_INVOKING": "1"
            }
        }
    }
    "terminal.integrated.defaultProfile.windows": "MSYS2_UCRT64",
    /*
      More stuff
    */
}

source: GitHub