Termbank
  1. A
    1. Abstraction
    2. Alias
    3. Argument
    4. Array
  2. B
    1. Binary code file
    2. Binary number
    3. Bit
    4. Bitwise negation
    5. Bitwise operation
    6. Byte
  3. C
    1. C library
    2. C-function
    3. C-variable
    4. Character
    5. Code block
    6. Comment
    7. Compiler
    8. Complement
    9. Conditional statement
    10. Conditional structure
    11. Control structure
  4. D
    1. Data structure
    2. Duck typing
  5. E
    1. Error message
    2. Exception
  6. F
    1. Flag
    2. Float
  7. H
    1. Header file
    2. Headers
    3. Hexadecimal
  8. I
    1. Immutable
    2. Initialization
    3. Instruction
    4. Integer
    5. Interpreter
    6. Introduction
    7. Iteroitava
  9. K
    1. Keyword
  10. L
    1. Library
    2. Logical operation
  11. M
    1. Machine language
    2. Macro
    3. Main function
    4. Memory
    5. Method
  12. O
    1. Object
    2. Optimization
  13. P
    1. Parameter
    2. Placeholder
    3. Pointer
    4. Precompiler
    5. Precompiler directive
    6. Prototype
    7. Python console
    8. Python format
    9. Python function
    10. Python import
    11. Python list
    12. Python main program
    13. Python variable
    14. Python-for
    15. Pääfunktio
    16. printf
  14. R
    1. Resource
    2. Return value
  15. S
    1. Statement
    2. Static typing
    3. String
    4. Syntax
  16. T
    1. Terminal
    2. Type
    3. Typecast
  17. U
    1. Unsigned
  18. V
    1. Value
  19. W
    1. Warning
    2. while
Completed: / exercises

Pointers

Learning Objectives: After going through this material, you will know how to use pointers in C and understand the significant benefits of their use in memory management for low-level programming.
Let's start with a brief review. When we introduce a variable in our program, for example, int8_t x = 42;, the following happens:

Pointer Variables

Pointers are a way to reference memory locations used by variables in a program. Previously, we worked with variables directly by assigning and manipulating their values. With pointers, instead of handling values directly, we can store and reference the memory address where a value is located. This allows us to access and modify the value at that memory address, providing more control over the program’s memory.
Let's clarify this with a hypothetical example where we have introduced and initialized two variables in the program, a and addressof_a.
uint8_t a = 0x42;
uint8_t *addressof_a = &a; // &-operator
Okay, so far, there's nothing unfamiliar to us, two variables a and addressof_a, each with its own memory location (hypothetical memory addresses 0x8E and 0x8F):
Variable Type Variable Name Memory Address Value
uint8_t a 0x8E 0x42
uint8_t* addressof_a 0x8F 0x8E
Now, the difference arises in how the values of these variables are interpreted:
By examining the example, we see that the value of the pointer variable addressof_a is actually the memory address of the variable a! This is called pointing / referring to the variable a. Pointing means that, when using the pointer variable, you "jump" to the memory location indicated by its value. We can still handle the variable a as a "regular" variable; nothing changes in that regard.
Example. Let's see what happens in the following:
#include <stdio.h>
#include <inttypes.h> // Derived data types from here

int main() {
   uint8_t a = 0x42;
   uint8_t *addressof_a = &a; 
   
   printf("The value of variable a is %x\n",a);
   printf("Pointer addressof_a points to the value %x\n",*addressof_a);
   // Change the value of a with assignment
   a = 0x56;
   printf("Pointer addressof_a points to the value %x\n",*addressof_a);
   // Change the value of a through the pointer with assignment
   *addressof_a = 0x78;
   printf("The value of variable a is %x\n",a);
   
   return 0;
}
And this prints:
The value of variable a is 42
Pointer addressof_a points to the value 42
Pointer addressof_a points to the value 56
The value of variable a is 78
Now, pointer variables provide an indirect way to reference memory allocated for another variable. As we will see, this is extremely useful for writing more efficient and compact code, which is particularly important in embedded programming due to resource constraints. (Additionally, since the value of a pointer variable can be any number, we can point anywhere in the memory available to the program.)
We will spend the rest of this lecture explaining the benefits of such "sorcery".

Pointer Operators

But first, let's go over some C syntax. The language provides two operators for working with pointer variables. These operators can be used to determine the address of any variable, initialize pointer variables to a desired address, and retrieve the values of the pointed memory locations.

Operator &

The & operator (address-of operator) is used to query the memory address of any variable. The syntax for the operator is &variable_name. Let's look at a code example on the lecturer's tax-deductible home PC:
int8_t a = 12;
printf("The value of a is %d and the memory address is %p",a,&a); 
...which outputs, The value of a is 12 and the memory address is 000000000023FE47 (64-bit architecture on the processor).

Operator *

The * operator has three purposes.
1. A pointer variable is declared using the * operator, i.e., the syntax *variable_name.
int8_t *addressof_a = &a; 
ATTENTION: If you declare a pointer but it is not initialized, the value of the the pointer is undefined that is, garbage value. An attempt to dereference (access the value it points to) would lead to undefined behaviour
int main() {
    int8_t *pointer_a;  // Declared but not initialized
    printf("Uninitialized pointer value: %p\n", pointer_a);  // This could print any arbitrary address
    return 0;
}
Instead, if we want to not initialize a pointer when we define it, we should initialize to NULL
int8_t *pointer_a = NULL;  // Now pointer_a is explicitly initialized to NULL
2. The assignment operator * is used to assign a new value to the memory location of the (other) variable pointed to.
int8_t a = 47;
int8_t *addressof_a = &a;
*addressof_a = 23; // change the value of a through the pointer
Now, a is initialized to 47, and then a new value of 23 is assigned to it using the pointer addressof_a. Interesting...
In contrast, assignment without the * operator addressof_a = 23 would change the value of the pointer variable itself so that it would point to memory location 23 instead of (necessarily) the memory location of variable a.
3. The * operator is used with pointer variables to retrieve the value of the memory location pointed to by the pointer variable (dereference operator).
uint16_t x = 0xBEEF;
uint16_t *addressof_x = &x;	
printf("x=%x\n",*addressof_x); 
This prints the retrieved pointed values.
x=beef

Pointer Variable Type

We can observe from the above that a pointer variable is always given a data type when it is declared. But, why? Isn't it just a memory address?
The data type is needed so that the compiler knows what type of value the pointer is pointing to at that memory location. Let's look at the following code example.
int main() {
   uint32_t a = 0x12345678;

   uint8_t *pointer_byte = &a; // 8-bit pointer
   uint16_t *pointer_word = &a; // 16-bit pointer
   uint32_t *pointer_longword = &a; // 32-bit pointer
	
   printf("%x\n",*pointer_byte);
   printf("%lx\n",*pointer_word);
   printf("%lx\n",*pointer_longword);
	
   return 0;
}
In the code, a 32-bit integer variable is declared, and it is assigned 8-, 16-, and 32-bit pointers. When the value of the variable pointed to by each pointer is printed (on the lecturer's PC), the following output is produced:
78        // 8-bit pointer returns a byte
5678      // 16-bit pointer returns a word
12345678  // 32-bit pointer returns a long word
We observe that the compiler understands the pointer based on its data type and retrieves the corresponding value from memory! Therefore, it is crucial to declare the pointer variable with the same data type as the variable it points to.
Note! When compiling the example code, you might encounter a warning about declaring a pointer of the wrong type warning: initialization from incompatible pointer type.
Note! Why isn't the output 12 or 1234?? This is due to the processor architecture's byte order. -> Little endian in this case.

Pointer Variable in Memory

Of course, like all variables, a pointer variable requires its own memory location. Let's revisit the previous example code with some modifications. Notice the placeholder %p, which can be used to print memory addresses.
#include <stdio.h>
#include <inttypes.h>

int main() {
   uint8_t a = 0x12;
   uint8_t *pointer_a = &a;

   // new operator: sizeof	
   printf("Memory address of variable a: %p\n",&a);
   printf("Size of variable in bytes: %d\n",sizeof(a));
    
   printf("Memory address of the pointer variable: %p\n",&pointer_a);
   printf("Size of the pointer variable in bytes: %d\n",sizeof(pointer_a));

   return 0;
}
Which prints (with real memory addresses):
Memory address of variable a: 0x7ffd6232a93f
Size of variable in bytes: 1
Memory address of the pointer variable: 0x7ffd6232a940
Size of the pointer variable in bytes: 8
From the output of the example, we see that each pointer variable has its own address in memory, and using the newly introduced sizeof operator, we can get the size of the pointer variable's memory location (8 bytes -> 64-bit processor architecture). The essential thing to notice here is that the size of the pointer variable's memory location is 4 bytes, regardless of the fact that it points to a variable that is only 1 byte in size.

Using Pointers

Okay, great. But why do we need pointer variables?

Pointers and Array Variables

Let’s examine the close relationship between pointer variables and arrays.
Since pointers allow us to freely access memory allocated to the program, we can, of course, also initialize pointer variables to point to elements of an array.
char string[] = "XYZ";	
char *ptr_1 = &string[0]; // now points to 'X'
char *ptr_2 = &string[1]; // now points to 'Y'
char *ptr_3 = &string[2]; // now points to 'Z'
printf("%c%c%c\n", *ptr_1, *ptr_3, *ptr_2);
This prints:
XZY
There’s more interesting stuff when initializing pointers with arrays.
int main() {
   char string[] = "XYZ";	
   char *method_1 = &string[0]; // initialization method 1
   char *method_2 = string;     // initialization method 2. Using Array Decay

   // Print the string
   printf("%s\n", string);
   printf("%s\n", method_1);
   printf("%s\n", method_2);
	
   return 0;
}
Since all two initialization methods point to the same memory address, the string output is the same:
XYZ
XYZ
XYZ
We can observe that, in C, when an array is used in an expression, the name of the array decays into a pointer to its first element. This observation will be useful for us soon...
However, arrays and pointers are not identical; arrays are a block of contiguous memory, while a pointer holds the address of some memory location. Importantly, you cannot change an array's name to point to another location, unlike pointers, which can be reassigned.
Now, let’s consider what happens when you pass an array to a function. When you pass an array to a function, only the pointer to the first element is passed (array decay), so the function has no idea how large the array is unless you explicitly tell it.
Here’s an example of a function that prints an array of integers, and we must pass both the array and its size:
#include <stdio.h>

// Function prototype: Takes a pointer to an array and its size
void print_array(int *array, int size);

int main() {
    int numbers[] = {10, 20, 30, 40, 50};  // Declare an array of integers
    int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate array size

    // Call the function with the array and its size
    print_array(numbers, size);

    return 0;
}

// Function to print array elements
void print_array(int *array, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
}
Attention: sizeof does not return the number of elements in an array but rather the total memory occupied by the array in bytes. To correctly calculate the number of elements, you should divide the total size of the array by the size of one element, like this:
int size = sizeof(numbers) / sizeof(numbers[0]);  // Correctly calculate the size here
You can always define the size of the array (e.g. a buffer) as a constant, and use it as an argument in size.

Pointer Arithmetic

Since the values of pointer variables are numerical values, we can, of course, manipulate them with all the arithmetic operations available in C.
For example:
int main() {
   char string[] = "ABCD";	
   char *ptr = string;

   // print each character in a loop..
   for (ptr = string; *ptr != 0; ptr++) {
      printf("%c",*ptr);
   }

   return 0;
}
The example code prints to the screen:
ABCD
Now is a good time to explain this example a bit:
What is remarkable is that arithmetic operations with pointers do not care about the variable type.
Example: In the following example, the ++ operator moves the pointer to the next element in the assignment statement ptr++.
#include <stdio.h>
#include <inttypes.h>

int main() {
   uint16_t array[] = { 0x1234, 0x5678, 0x9ABC };
   uint16_t *ptr = array; 

   for (ptr = array; *ptr != 0; ptr++) {
      printf("%lx ",*ptr);
   }
        
   return 0;
}
This prints:
1234 5678 9abc 
When you increment a pointer, the amount by which it increases depends on the size of the data type it points to. For example, incrementing a char * pointer moves it by 1 byte (since char is 1 byte), while incrementing a uint16_t * pointer moves it by 2 bytes (because uint16_t is 2 bytes).
This also highlights how C is truly a low-level hardware-oriented language. We can freely access the memory of our program and manipulate the values of variables and their memory addresses.
As a result, a C programmer must be very careful not to break anything while working with pointers. For example, we might accidentally point to a memory location outside the variable’s allocated memory space, inadvertently modifying another variable’s value (overflow), or even outside the memory space allocated for the entire embedded program, which could lead to crashes.

As Function Arguments

Just like any other variable type, pointers can also be used as function parameters. Essentially, the argument passed to the function is the memory address, which is stored in the function's local variable. This is extremely useful as we will soon see...
Let’s start with an example... the function swap below does not work. Why?
#include <stdio.h>

void swap(int8_t local_a, int8_t local_b); // prototype

int main() {
   int8_t a = 14;
   int8_t b = 68;
   printf("Before: a=%d and b=%d\n", a, b);
   swap(a, b);
   printf("After: a=%d and b=%d\n", a, b);
}

void swap(int8_t local_a, int8_t local_b) {
   int8_t temp = local_a;
   local_a = local_b;
   local_b = temp;
}
This prints:
Before: a=14 and b=68
After: a=14 and b=68
The explanation for this can be found in the Functions in C material from earlier lectures. We remember that in C, a function creates copies of the arguments in local variables. In the above code, we are only swapping the values of the copies (the variables local_a and local_b), not the values of the original variables a and b.
No worries. This issue can be fixed by using pointers as function arguments. Now, in the function, the pointer local_a points to the memory address of a passed as an argument.
#include <stdio.h>

void swap(int8_t *a, int8_t *b); // pointer prototype

int main() {
   int8_t a = 14;
   int8_t b = 68;

   printf("Before: a=%d and b=%d\n", a, b);
   swap(&a, &b); // Note the use of the & operator
   printf("After: a=%d and b=%d\n", a, b);
}

void swap(int8_t *local_a, int8_t *local_b) {
   int8_t temp = *local_a; // save the value pointed to by a
   *local_a = *local_b;    // set the value pointed to by a to the value of b
   *local_b = temp;        // set the value of b to the original value of a
}
Now the program prints:
Before: main_a=14 and main_b=68
After: main_a=68 and main_b=14

Memory Savings

In the same way, pointers can also significantly save memory!
Let’s recall an example from earlier material, where we passed a struct with a large array as an argument to a function, and the poor function tried to obediently make a copy of it each time.
// Define a struct for the message
typedef struct {
    char destination_address[4];  // 4-byte address
    char message[2048];           // 2-kilobyte message
} Message;

...
// Declare a message struct and fill it with data
Message message_home = {"ABCD", "This is the message content..."};
...
// Call the function with the struct as an argument (passing by reference)
send_message(message_home);
...
This issue can be conveniently fixed by passing the address of the struct as an argument:
// Define a struct for the message
typedef struct {
    char destination_address[4];  // 4-byte address
    char message[2048];           // 2-kilobyte message
} Message;

// Function prototype
void send_message(Message *message_home);

int main() {
    // Declare a message struct and fill it with data
    Message message_home = {"ABCD", "This is the message content..."};
    
    // Call the function with the struct as an argument (passing by reference)
    send_message(&message_home);

    return 0;
}
Note! Of course, the function makes a copy of the pointer variable, but a pointer type (which is 8 bytes in size) is much smaller than the array itself.

Returning from a Function

Let’s return briefly to the previously discussed swap function, as it reveals another interesting thing...
void swap(int8_t *a, int8_t *b) {
   int8_t temp = *a;
   *a = *b;
   *b = temp;
}
In this function, we’re actually returning two values as the result of the function’s execution, namely the swapped values of variables a and b. In this way, we circumvent C’s limitations by directly manipulating memory instead of the variables themselves. Super convenient!
Note! We can also return a memory address from a function. But, make sure the pointer refers to valid memory (e.g., dynamically allocated memory or a global variable). Returning a pointer to a local variable in a function is unsafe, as the memory becomes invalid once the function exits.

String Handling

One of the key benefits of pointers is evident in handling strings.
As part of the standard library, the library string.h defines a set of useful functions for working with strings:
#include <stdio.h>
#include <string.h>

int main() {

  char name[] = "Judge Dredd";
  printf("The length of the name %s is %d characters\n", name, strlen(name));

  return 0;
}
All these library functions accept strings as pointers through their variable names. In other words, they assume that the given array always ends with a null character and therefore do not require the size of the array as a parameter. This, of course, can be dangerous if you are working with strings that do not end with a null character. So be careful!!!

Convenience for Low-Level Programming

Finally, here's an example of the strtok function, because it is extremely useful in embedded systems.
As noted earlier, data structures and wireless messages often follow the CSV format, where different fields in the message are separated by commas.
For example: 1234567890,temperature,27,C, where the first field is the timestamp (i.e., when the sensor value was measured), followed by the sensor type (temperature), measurement value (27), and measurement unit (Celsius).
Now, breaking down such a CSV-formatted string into parts is easily done with the strtok function.
#include <string.h>
#include <stdio.h>

int main () {
  char str[] = "1234567890,temperature,27,C"; 
  const char sep[] = ",";  // Separator is a comma
  char *token; // Placeholder pointer
   
  // Extract the first part of the message
  token = strtok(str, sep);
   
  // Loop to extract the remaining parts
  while( token != NULL ) {
    printf("%s\n",token);

    // Call the function again, continue from the placeholder
    token = strtok(NULL, sep);
    }
   
  return(0);
}
Let’s see what the example prints!
1234567890
temperature
27
C
Note: strok does not work in an intiutive way. You can find further explanation on how it works here
In the example, it's important to note that the separated parts are still strings. To process the numerical values in the message as numbers, we need to convert the strings to integer or floating-point variable types.
For this, the standard library stdlib.h provides functions such as atoi for integers, atol for long integers, and atof for floating-point numbers. Some of these functions are based on older C standards, but we can still use them. Modern system uses strtol and strtod.
#include <stdio.h>
#include <stdlib.h>

int main () {
  char str[] = "1234567890"; 
  
  long value = atol(str);
  printf("%ld\n",value);
   
  return(0);
}
However, in embedded development environments, these standard library functions might be replaced by other functions, or there might be limitations in their implementation.

In Conclusion

Help
This material provided a sufficient introduction to pointers in C for the course. They have more secrets... such as command line arguments, (multi-dimensional) pointer arrays, and function pointers, which we won't cover in the course. For those interested in learning more about pointers, additional information can be found in textbooks.
?
Abstraction is a process through which raw machine language instructions are "hidden" underneath the statements of a higher level programming language. Abstraction level determines how extensive the hiding is - the higher the abstraction level, the more difficult it is to exactly say how a complex statement will be turned into machine language instructions. For instance, the abstraction level of Python is much higher than that of C (in fact, Python has been made with C).
Alias is a directive for the precompiler that substitus a string with another string whenever encountered. In it's basic form it's comparable to the replace operation in a text editor. Aliases are define with the #define directeve, e.g. #define PI 3.1416
Argument is the name for values that are given to functions when they are called. Arguments are stored into parameters when inside the function, although in C both sides are often called just arguments. For example in printf("%c", character); there are two arguments: "%c" format template and the contents of the character variable.
Array is a common structure in programming languages that contains multiple values of (usually) the same type. Arrays in C are static - their size must be defined when they are introduced and it cannot change. C arrays can only contain values of one type (also defined when introduced).
Binary code file is a file that contains machine language instructions in binary format. They are meant to be read only by machines. Typically if you attempt to open a binary file in a text editor, you'll see just a mess of random characters as the editor is attempting to decode the bits into characters. Most editors will also warn that the file is binary.
Binary number is a number made of bits, i.e. digits 0 and 1. This makes it a base 2 number system.
A bit is the smallest unit of information. It can have exactly two values: 0 and 1. Inside the computer everything happens with bits. Typically the memory contains bitstrings that are made of multiple bits.
Bitwise negation is an operation where each bit of a binary number is negated so that zeros become ones and vice versa. The operator is ~.
Bitwise operations are a class of operations with the common feature that they manipulate individual bits. For example bitwise negation reverses each bit. Some operations take place between two binary values so that bits in the same position affect each other. These operations include and (&), or (|) and xor (^). There's also shift operations (<< and >>) where the bits of one binary number are shifted to the left or right N steps.
Byte is the size of one memory slot - typically 8 bits. It is the smallest unit of information that can be addressed from the computer's memory. The sizes of variable types are defined as bytes.
External code in C is placed in libraries from which they can be taken to use with the #include directive. C has its own standard libraries, and other libraries can also be included. However any non-standard libraries must be declared to the compiler. Typically a library is made of its source code file (.c) and header file (.h) which includes function prototypes etc.
Functions in C are more static than their Python counterparts. A function in C can only have ne return value and its type must be predefined. Likewise the types of all parameers must be defined. When a function is called, the values of arguments are copied into memory reserved for the function parameters. Therefore functions always handle values that are separate from the values handled by the coe that called them.
C variables are statically typed, which means their type is defined as the variable is introduced. In addition, C variables are tied to their memory area. The type of a variable cannot be changed.
Character is a single character, referred in C as char. It can be interpreted as an ASCII character but can also be used as an integer as it is the smallest integer that can be stored in memory. It's exactly 1 byte. A character is marked with single quotes, e.g. 'c'.
Code block is a group of code lines that are in the same context. For instance, in a conditional structure each condtion contains its own code block. Likewise the contents of a function are in their own code block. Code blocks can contain other code blocks. Python uses indentation to separate code blocks from each other. C uses curly braces to mark the beginning and end of a code block.
Comments are text in code files that are not part of the program. Each language has its own way of marking comments. Python uses the # character, C the more standard //. In C it's also possible to mark multiple lines as comments by placing them between /* and */.
A compiler is a program that transforms C source code into a binary file containing machine language instructions that can be executed by the computer's processor. The compiler also examines the source code and informs the user about any errors or potential issues in the code (warnings). The compiler's behavior can be altered with numerous flags.
Complement is a way to represent negative numbers, used typically in computers. The sign of a number is changed by flipping all its bits. In two's complement which is used in this course, 1 is added to the result after flipping.
Conditional statement is (usually) a line of code that defined a single condition, followed by a code block delimited by curly braces that is entered if the condition evaluates as true. Conditional statements are if statements that can also be present with the else keyword as else if. A set of conditional statements linked together by else keywords are called conditional structures.
Conditional structure is a control structure consisting of one or more conditional statements. Most contrl structures contain at least two branches: if and else. Between these two there can also be any number of else if statements. It is however also possible to have just a single if statement. Each branch in a conditional structure cotains executable code enclosed within a block. Only one branch of the structure is ever entered - with overlapping conditions the first one that matches is selected.
Control structures are code structures that somehow alter the program's control flow. Conditional structures and loops belong to this category. Exception handling can also be considered as a form of control structure.
Data structure is a comman name for collection that contain multiple values. In Python these include lists, tuples and dictionaries. In C the most common data structures are arrays and structs.
Python's way of treating variable values is called dynamic typing aka duck typing. The latter comes from the saying "if it swims like a duck, walks like a duck and quacks like a duck, it is a duck". In other words, the validity of a value is determined by its properties in a case-by-case fashion rather than its type.
An error message is given by the computer when something goes wrong while running or compiling a program. Typically it contains information about the problem that was encountered and its location in the source code.
An exception is what happens when a program encounters an error. Exceptions have type (e.g. TypeError) that can be used in exception handling within the program, and also as information when debugging. Typically exceptions also include textual description of the problem.
Flags are used when executing programs from the command line interface. Flags are options that define how the program behaves. Usually a flag is a single character prefixed with a single dash (e.g. -o) or a word (or multiple words connected with dashes) prefixed with two dashes (e.g. --system. Some flags are Boolean flags which means they are either on (if present) or off (if not present). Other flags take a parameter which is typically put after the flag separated either by a space or = character (e.g. -o hemulen.exe.
Floating point numbers are an approximation of decimal numbers that are used by computers. Due to their archicture computers aren't able to process real decimal numbers, so they use floats instead. Sometimes the imprecision of floats can cause rounding errors - this is good to keep in mind. In C there are two kinds of floating point numbers: float and double, where the latter has twice the number of bits.
Header files use the .h extension, and they contain the headers (function prototypes, type definitions etc.) for a .c file with the same name.
Headers in C are used to indicate what is in the code file. This includes things like function prototypes. Other typical content for headers are definition of types (structs etc.) and constants. Headers can be at the beginning of the code file, but more often - especially for libraries - they are in placed in a separate header (.h) file.
Hexadecimal numbers are base 16 numbers that are used particularly to represent memory addresses and the binary contents of memory. A hexadecimal number is typically prefixed with 0x. They use the letters A-F to represent digits 10 to 15. Hexadecimals are used because each digit represents exactly 4 bits which makes transformation to binary and back easy.
In Python objects were categorized into mutable and immutable values. An immutable value cannot have its contents changed - any operations that seemingly alter the object actually create an altered copy in a new memory location. For instance strings are immutable in Python. In C this categorization is not needed because the relationship of variables and memory is tighter - the same variable addresses the same area of memory for the duration of its existence.
When a variable is given its initial value in code, the process is called initialization. A typical example is the initialization of a number to zero. Initialization can be done alongside with introduction: int counter = 0; or separately. If a variable has not been initialized, its content is whatever was left there by the previous owner of the memory area.
Instruction set defines what instructions the processor is capable of. These instructions form the machine language of the processor architecture.
Integers themselves are probably familiar at this point. However in C there's many kinds of integers. Integer types are distinguished by their size in bits and whether they are signed or not. As a given number of bits can represent up to (2 ^ n) different integers, the maximum value for a signed integer is (2 * (n - 1))
Python interpreter is a program that transforms Python code into machine language instructions at runtime.
The moment a variable's existence is announed for the first is called introduction. When introduced, a variable's type and name must be defined, e.g. int number;. When a variable is introduced, memory is reserved for it even though nothing is written there yet - whatever was in the memory previously is still there. For this reason it's often a good idea to initialize variables when introducing them.
Iteroitava objekti on sellainen, jonka voi antaa silmukalle läpikäytäväksi (Pythonissa for-silmukalle). Tähän joukkoon kuuluvat yleisimpinä listat, merkkijonot ja generaattorit. C:ssä ei ole silmukkaa, joka vastaisi Pythonin for-silmukan toimintaa, joten taulukoiden yms. läpikäynti tehdään indeksiä kasvattavilla silmukoilla.
Keywords are words in programming languages that have been reserved. Good text editors generally use a different formatting for keywords (e.g. bold). Usually keywords are protected and their names cannot be used for variables. Typical keywords include if and else that are used in control structures. In a way keywords are part of the programming language's grammar.
A library is typically a toolbox of functions around a single purpose. Libraries are taken to use with the include directive. If a library is not part of the C standard library, its use must also be told to the compiler.
Logical operation refers to Boole's algebra, dealing with truth values. Typical logical operations are not, and, or which are often used in conditional statements. C also uses bitwise logical operations that work in the same way but affect each bit separately.
Machine language is made of instructions understood by the processor. Machine language is often called Assembly and it is the lowest level where it's reasonable for humans to give instructions to computers. Machine language is used at the latter part of this course - students taking the introduction part do not need to learn it.
Macro is an alias that defines a certain keyword to be replaced by a piece of code. When used well, macros can create more readable code. However, often the opposite is true. Using macros is not recommended in this course, you should just be able to recognize one when you see it.
In C the main function is the starting point when the program is run. The command line arguments of the program are passed on to the main function (although they do not have to be received), and its return value type is int. At its shortest a main function can defined as int main().
When programs are run, all their data is stored in the computer's memory. The memory consists of memory slots with an address and contents. All slots are of equal size - if an instance of data is larger, a continuous area of multiple memory slots is reserved.
Method is a function that belongs to an object, often used by the object to manipulate itself. When calling a method, the object is put before the method: values.sort().
Object is common terminology in Python. Everything in Python is treated as objects - this means that everything can be referenced by a variable (e.g. you can use a variable to refer to a function). Objects are typically used in object-oriented languages. C is not one.
Optimization means improving the performance of code, typically by reducing the time it takes to run the code or its memory usage. The most important thing to understand about opimization is that it should not be done unless it's needed. Optimization should only be considered once the code is running too slowly or doesn't fit into memory. Optimization should also not be done blindly. It's important to profile the code and only optimize the parts that are most wasteful.
A parameter is a variable defined alongside with a function. Parameters receive the values of the function's arguments when it's called. This differentation between parameters and arguments is not always used, sometimes both ends of the value transfer are called arguments.
Placeholders are used in string formatting to mark a place where a value from e.g. a variable will be placed. In Python we used curly braces to mark formatting placeholders. In C the % character is used which is followed by definitions, where the type of the value is mandatory. For instance "%c" can only receive a char type variable.
Pointers in C are special variables. A pointer contains a memory address of the memory location where the actual data value is located. In a sense they work like Python variables. A variable can be defined as a pointer by postfixing its type with * when it's being introduced, e.g. int* value_ptr; creates a pointer to an integer. The contents of the memory address can be fetched by prefixing the variable name with * (e.g. *value_ptr. On the other hand, the address of a memory adress can be fetched by prefixing a variable name with &, (e.g. &value.
The C precompiler is an apparatus that goes through all the precompiler directives in the code before the program is actually compiled. These directives include statements which add the source code of the included libraries into the program, and define directives that can define constant values (aliases) and macros.
Directives are instructions that are addressed at the precompiler. They are executed and removed from the code before the actual compilation. Directives start with the # character. The most common one is include which takes a library into use. Another common one is define, which is used e.g. to create constant values.
Prototype defines a function's signature - the type of its return value, its name and all the arguments. A prototype is separate from the actual function definition. It's just a promise that the function that matches the prototype will be found in the code file. Prototypes are introduced at the beginning of the file or in a separate header file. In common cases the prototype definition is the same as the line that actually starts the function introduction.
Interactive interpreter or Python console is a program where users can write Python code lines. It's called interactive because each code line is executed after its been fully written, and the interpreter shows the return value (if any).
The format method of string in Python is a powerful way to include variable values into printable text. The string can use placeholders to indicate where the format method's arguments are placed.
Python functions can have optional parameters that have a given default value. In Python the values of arguments in a function call are transferred to function parameters through reference, which means that the values are the same even though they may have different names. Python functions can have multiple return values.
In Python the import statement is used for bringing in modules/libraries - either built-in ones, thrid party modules or other parts of the same application. In Python the names from the imported module's namespace are accessible through the module name (e.g. math.sin). In C libraries are taken to use with include, and unlike Python import it brings the library's namespace into the program's global namespace.
Python lists were discovered to be extremely effective tools in Elementary Programming. A Python list is an ordered collection of values. Its size is dynamic (i.e. can be changed during execution) and it can include any values - even mixed types. Lists can also include other lists etc.
In Python main program is the part of code that is executed when the program is started. Usually the main program is at the end of the code file and most of the time under if __name__ == "__main__": if statement. In C there is no main program as such, code execution starts with the main function instead.
In Python a variable is a reference to a value, a connection between the variable's name in code and the actual data in memory. In Python variables have no type but their values do. The validity of a value is tested case by case when code is executed. In these ways they are different from C variables, and in truth Python variables are closer to C pointers.
Pythonin for-silmukka vastaa toiminnaltaan useimmissa kielissä olevaa foreach-silmukkaa. Se käy läpi sekvenssin -esim. listan - jäsen kerrallaan, ottaen kulloinkin käsittelyssä olevan jäsenen talteen silmukkamuuttujaan. Silmukka loppuu, kun iteroitava sekvenssi päättyy.
Pääfunktio on C:ssä ohjelman aloituspiste ja se korvaa Pythonista tutun pääohjelman. Oletuksena pääfunktion nimi on main ja se määritellään yksinkertaisimmillaan int main().
Resource referes to the processing power, memory, peripheral devices etc. that are availlable in the device. It includes all the limitations within which programs can be executed and therefore defines what is possible with program code. On a desktop PC resources are - for a programmer student - almost limitless, but on embedded devices resources are much more scarce.
Return value is what a function returns when its execution ends. In C functions can only have one return value, while in Python there can be multiple. When reading code, return value can be understood as something that replaces the function call after the function has been executed.
A statement is a generic name for a single executable set of instructions - usually one line of code.
C uses static typing This means that the type of variables is defined as they are created, and values of different types cannot be assigned to them. The validity of a value is determined by its type (usually done by the compiler). Python on the other hand uses dynamic typing aka.duck typing.
In Python all text is handled as strings and it has no type for single characters. However in C there are no strings at all - there's only character arrays. A character array can be defined like a string however, e.g. char animal[7] = "donkey"; where the number is the size of the array + 1. The +1 is neede because the string must have space for the null terminator '\0' which is automatically added to the end of the "string".
Syntax is the grammar of a programming language. If a text file does not follow the syntax of code, it cannot be executed as code, or in the case of C, it cannot be compiled.
Terminal, command line interface, command line prompt etc. are different names to the text-based interface of the operating system. In Windows you can start the command line prompt by typing md to the Run... window (Win+R). Command line is used to give text-based commands to the operating system.
The data in a computer's memory is just bits, but variables have type. Type defines how the bits in memory should be interpreted. It also defines how many bits are required to store a value of the type. Types are for instance int, float and char.
Typecast is an operation where a variable is transformed to another type. In the elementary course this was primarily done with int and float functions. In C typecast is marked a bit differently: floating = (float) integer}. It's also noteworthy that the result must be stored in a variable that is the proper type. it is not possible to change the type of an existing variable.
Unsigned integer is a an integer type where all values are interpreted as positive. Since sign bit is not needed, unsigned integers can represent twice as large numbers as signed integers of the same size. An integer can be introduced as unsigned by using the unsigend keyword, e.g. unsigned int counter;.
In the elementary programming course we used the term value to refer to all kinds of values handled by programs be it variables, statement results or anything. In short, a value is data in the computer's memory that can be referenced by variables. In C the relationship between a variable and its value is tighter as variables are strictly tied to the memory area where its value is stored.
A warning is a notification that while executing or - in this course particularly - compiling it, something suspicious was encountered. The program may still work, but parts of it may exhibit incorrect behavior. In general all warnings should be fixed to make the program stable.
One way to print stuff in C is the printf function, which closely resembles Python's print function. It is given a printable string along with values that will be formatted into the string if placeholders are used. Unlike Python, C's printf doesn't automatically add a newline at the end. Therefore adding \n at the end is usually needed.
Out of loops, while is based on repetition through checking a condition - the code block inside the loop is repeated until the loop's condition is false. The condition is defined similarly to conditional statements, e.g. while (sum < 21).