C Flashcards

Week 2.4, 2.5, 2.6, 2.7, 2.8 (163 cards)

1
Q

why level language is C

A

low-level, high-level

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

why is C high-level

A

we can write code in a natural language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

why is C low-level

A

we can precisely control use of and access to memory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what programming paradigm is C

A

imperative

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what are available in C and not in python

A

pointers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

for both python and C are they compiled or interpreted

A

python - interpreted
C - compiled

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

define byte-code

A
  • abstraction of machine code
  • platform independent and portable
  • cannot run directly on hardware
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

libraries in C syntax

A

include <stdio.h></stdio.h>

#include <math.h></math.h>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

how are functions scope defined

A

{}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

what is not relevant in C

A

indentation - but still highly advised for readability

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

what is needed after every C line

A

;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

what do we use to compile C

A

GNU compiler collection - gcc

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

what does the compiler do

A

converts plain-text source code to a file of executable mahine code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

what are the 2 type of compiler messages

A
  1. errors
  2. warnings
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

what is a compiler message error

A
  • fatal to the compilation process
  • language syntax errors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

what is a compiler message warning

A
  • may not be fatal but indicate issues to address
  • may still produce an executable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

what are 3 primitive data types in C

A
  1. int
  2. float
  3. char
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

define static typing

A
  • type of variable determined at compile-time & remains fixed
  • produces more efficient compiled code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

define dynamic typing

A
  • type of variable is determined at run-time & can be changed
  • problematic due to mis-matches
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

define strong typing

A
  • type of variable must be declared
  • different types of variable cannot be mixed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

define weak typing

A
  • type of variable not needed to be declared
  • different types of variables can be combined - implicit type conversion
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

what typing does C use

A

statically & weakly typed
- BUT has elements of strong typing - variable declaration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

how is C stored in memory

A
  • C language standard does not define how much each memory type uses
    ○ They are generally constrained by machine architecture
    ○ and by the compiler and machine-specific language definition
  • sets a minimum
  • further reason that C is not fully portable between platforms
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

3 types of integers & their sizes

A
  1. int = 4 bytes minimum
  2. short int = 2 bytes
  3. long int = 8 bytes
    - also unsigned int types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
3 types of floating-points & their sizes
1. float = 4 bytes 2. double = 8 bytes 3. long double = 16 bytes
26
define a character
- 1 byte - integer ASCII character code stored in the variable
27
what is a string actually in C
a character array
28
sizeof()
returns the number of bits used in a data item
29
what is the variable value
data stored in the variable - accessed through x
30
what is the variable address
location in memory of the variable - accessed through &x
31
define pointer data type
- stores a memory address - uses number of bytes determined by architecture
32
what is a pointer's value
location in memory - p
33
what is a pointer's target
item stored at the memory location - *p
34
*
dereferences a pointer
35
uses of pointers
- dynamic memory allocation - creating self-referential data structures
36
misuse of pointers
not 'memory-safe' - requirement to manually manage memory - ability to query and alter data in other memory locations
37
example of casting
int k = 4; float d = (float)k;
38
example of implicit casting
int k = 4; float d = 3.0' float e = d/k;
39
what type of casting is bad programming practice
implicit - leads to numerical inaccuracy
40
what are the 2 derived data types
1. pointer 2. array
41
why is a pointer a derived data type
address of a primitve data type
42
why is an array a derived data type
collection of primitive data types
43
how are arrays typed in C
- statically - one type of data
44
what are the 2 ways to define arrays in C
1. at compile time - as static arrays 2. at run-time - as dynamic arrays
45
what are the 2 types of memory C programs access
1. the stack 2. the heap
46
what is the stack memory
memory reserved for static program data - managed by the compiler - LIFO - used for statically declared variables & arrays
47
what is the heap memory
memory available for dynamic program data - access through pointers - flexible unordered address space - used for dynamically declared variables & arrays
48
syntax to declare a static array
int vec[5];
49
how are static arrays stored in memory
- compiler allocates contiguous space for the array in the stack - size of arrays is fixed, once declared
50
for loop syntax
for (int k = 0; k < n; k++){ //code }
51
syntax for initialising a static array using a for loop
int vec[5]; for (int k = 0; k < 5; k++){ vec[k] = 2 - k; }
52
syntax for initialising a static array inline
int vec[5] = {2, 1, 0, -1, -2} OR int vec[] = {2, 1, 0, -1, 2}
53
syntax declare a 2-dimensional static array
int mat[5][5];
54
how should we access memory in terms of 2-dimensional arrays
- access arrays such that the right-most index varies fastest - reduces page faulting - important for high-performance applications
55
what do we need to add to a char array to make it a string
"\0" - as the last entry - adds one element to the array - signifies the end of the string
56
syntax to define strings
char word[6] = {"h", "e", "l", "l", "o", "\0"} OR char word[] = {"h", "e", "l", "l", "o", "\0"} OR char word[] = "hellol";
57
syntax to declare a variable length string
char buffer[100] = "hello";
58
describe variable-length arrays
- i.e float mat[m][n]; - but the size parameter n and m can be defined at run-time - uses stack memory which is more limited than heap memory - not resizable once allocated
59
what 2 things do dynamic arrays need
1. pointers 2. heap memory
60
what are the 3 utility functions needed to allocate memory on the heap
1. malloc - allocate an item of a given type 2. calloc - allocate an array of a given type 3. free - release allocated memory
61
what library is needed for allocating memory on the heap
#include
62
syntax to declare a pointer
int *kp;
63
malloc syntax
kp = malloc(sizeof(int)); - allocates an int on the heap
64
calloc syntax
kp = calloc(24, sizeof(int)); - allocate an array of 24 units on the heap - stored contiguously - array does not exist until the statement is executed
65
realloc syntax
kp = realloc(kp, 36*sizeof(int)); - exisitng array maintained - address in kp unchanged
66
what does realloc() do
adjust the length of an array
67
what is garbage collection
allocate and deallocate dynamic memory silently
68
describe automated garbage collection
- virtual machine determines when to allocate and deallocate memory - extra resource is required for your program to manage this - don’t know when memory is deallocated
69
what does C use for garbage collection
depends on programmer/code - know precisely how much we are using at any point - create fatal errors if we get it wrong - another reason why C is not considered memory-safe
70
syntax to define a multi-dimensional dynamic array
int **mat; mat = calloc(24, sizeof(int *)); for( int i = 0; i < 24; i++){ mat[i] = calloc(36, sizeof(int)); }
71
what is array-pointer duality
pointers link between static & dynamic memory
72
array pointer duality on the stack
&(vec[0]) == vec
73
int vec[24]
a static integer array of 24 int values
74
vec[0]
the value of the first element of the array
75
&(vec[0])
address of the first element
76
vec
address of the start of the array - i.e first element
77
array-pointer duality on the heap
int *vec = calloc(24, sizeof(int)); - pointer vec stores address of the start of the array - access array using vec[0], vec[1]
78
define argc
int - the number of arguments - always at least 1
79
define argv
- array of strings, containing the arguments - argv[0] is the program itself - dynamically allocated by the operating system when the program runs - an array of strings in C
80
atoi()
int i = atoi(argv[1]); - converts a string to an int
81
atof()
double f = atof(argv[1]); - converts a string to a double
82
how do you make a safe command-line input
- whenever we expect command line input - we should always verify that enough arguments are given
83
6 general guidelines for coding style & conventions
1. comments 2. naming of data items 3. brackets 4. indentation 5. whitespace 6. consistency
84
what are the 2 types of comments for in c
1. detailed explanation 2. inline - explanation of a specific operation
85
syntax for docstrings/detailed explanation in C
/* ... */
86
how do we improve readability
- use spaces inline - use clear lines between lines to section code
87
what are the 3 types of flow control
1. sequential 2. conditional 3. repetition
88
why does flow control matter?
- enables complex decision-making - makes programs dynamic and responsive
89
boolean logic on C89/C()
0 = false 1 = true
90
boolean logic in C99
#include - true, false, bool
91
AND syntax
&&
92
OR syntax
||
93
NOT syntax
!
94
what are the 3 types of if statement
1. if 2. if-else 3. else-if
95
if syntax
if (condition){ //code }
96
if-else syntax
if (condition){ //code } else{ //code }
97
else-if syntax
if (condition){ //code }else if (condition){ //code } else{ //code }
98
what is the standard input function
scanf()
99
characteristics of scanf()
- requires address-of (&) operator - different format specifiers for different types - reads input into memory locations - can read multiple inputs in one call
100
integer format specifier
"%d"
101
float format specifier
"%f"
102
character format specifier
" %c" - space needed
103
string format specifer
"%s"
104
syntax for using scanf()
int number; char resposne; scanf("%d", &number); scanf(" %c", &response);
105
switch statement syntax
switch (expression) { case value1: //code break; case value2: //code break; default: //code }
106
what is short circuit evaluation
- && and || evaluate only what is necessary - A&&B: if A is false, B is not evaluated - A||B: if A is true, B is not evaluated
107
what is short-circuit evaluation useful for
preventing errors - input - pointer
108
how to debug conditional statements
- add printf statements to verify condition values - test boundary values - test all paths through conditionals - use parentheses to clarify complex conditions
109
how is counting down expressed in for loops
k---
110
how is a custom increment represented in for loops
i +=2
111
while loop syntax
while (condition) { //code }
112
while loop to check for an error
int number; printf("enter a positive number: "); scanf("%d", &number); while (number <=0) { printf("Invalid! Enter a positive number: "); scanf("%d", &number); }
113
do while loop syntax
do { //code } while (condition);
114
use of do while
- unknown number of iterations - post-test condition - always executed at least once
115
input handling process with fgets()
1. allocate buffer of approporiate size 2. reads inputs with fgets() 3. process the input 4. handle error conditions gracefully
116
fgets() syntax
char *fgets( char *str, int size, FILE *stream);
117
checking for an error with fgets()
char input[50]; printf("Enter text (CTRL + D for EOF): "); if (fgets( input, sizeof(input), stdin) == NULL) { printf("Error reading input or EOF reached.") }
118
removing newline character
name[strcspn(name, "\n")] = "\0";
119
function definition syntax
returnType functionName( type arg1, type arg2, ...) { //code return something; }
120
main function defintion
int main (int argc, char **argv) { ... return 0; }
121
procedure definition syntax
void functionName( type arg1 ...) { ... }
122
code to write to a file
#include int main(){ FILE *file = fopen("example.txt", "w"); if (file == NULL) { printf("Error: File not found.\n"); return 1; } fprintf(file, "Hello World!\n"); fclose(file); return 0; }
123
code to read from a file
#include int main() { FILE *file = fopen("example.txt", "r"); char buffer[100]; if (file == NULL) { printf("Error: File not found.\n"); return 1; } while fgets(buffer, sizeof(buffer), file) != NULL){ printf("%s", buffer); } fclose(file); return 0; }
124
what programming language is preferred for text-handling
python is generally preferred for text-handling programs because strings are a native type and there is a better range of built-in functions
125
why do we pass by reference
to update the value
126
how do we pass by reference
by passing the pointer to the variable
127
passing by reference code example
void add (int a, int b, int* answer}{ *answer = a + b; } int main(void) { int num1 = 10, num2 = 5, result = 0; add(num1, num2, &result); printf("%d\n", result); return 0; }
128
how are arrays passed into functions
always passed by reference -when you pass an array into another function it becomes a pointer to the first element
129
what is unit testing
testing individual functions to ensure they respond correctly to inputs
130
library needed for assert()
#include
131
example of using assert()
assert(add(2, 3) == 5); assert(add(-1, 1) == 0); printf("All tests passed!\n")
132
what is assert() used for
- check outputs from functions, and ensure they are correct - checking the result of a mathematical operation - check for error returns
133
what are structures
- collections of related variables under one name - allow custom data types for complex data - enhance code organisation & readability - model real-world entities with appropriate attributes
134
example of structure syntax
struct Person { char name[50]; int age; float height; }; struct Person person1 = {"Izzy", 19, 1.66} printf("Name: %s\n", person1.name);
135
typedef
creates aliases for structure types - follows same rules as primitive data types = strong typing
136
example of typedef syntax
typedef struct { int x; int y; } Point; Point p2;
137
what do structure pointers enable
- efficient parameter passing (by reference) - dynamic memory allocation - linked data structures
138
(*ptr).structName
dereference then access
139
ptr -> structName
arrow notation (preferred)
140
example use of structure pointers
typedef struct { int x; int y; } Point; Point p1 = {10, 20}; Point *ptr = &p1; printf("x = %d\n", (*ptr).x); printf("y = %d\n", ptr -> y);
141
example of a dynamically allocated structure using pointers
Point * p2 = (Point *)malloc(sizeof(Point)); p2 -> x = 5; p2 -> y = 15; free(p2);
142
self-referential structures
a structure that contains a pointer to its own structure
143
linked list code
typedef struct Node{ int data; struct Node* next; }Node; Node* create_node( int value){ Node* new_node = (Node*)malloc( sizeof(Node)); new_node -> data = value; new_node -> next = NULL; return new_node; } Node* head = create_node(10); head -> next = create_node(20); head -> next -> next = create_node(30);
144
where should the main function be located in a small program
main should be at the top for small, single-file programs
145
how is C code organised in larger programs
project/ - include/ (header files) - src/ (implementation files .c) - obj/ (compiled object files .o) - bin/ (executable output) - Makefile (build instructions) - README.md (project documentation)
146
what is included in header files
1. structure definitions 2. function prototypes 3. constants & macros 4. type definitions
147
example of a header file
#ifndef STUDENT_H #define STUDENT_H #define MAX_NAME_LENGTH 50 # define NUM_MODULES 4 /* Add necessary includes here */ /* Add constant definitions here */ /* Add structure definitions here */ /* Add function prototypes here */ #endif /*STUDENT_H*/
148
what do implementation files include
1. related headers 2. function implementations 3. private helper functions 4. static variables
149
what does the main program file include
1. necessary headers 2. contains main() function 3. minimal implementation logic
150
what do header files need to include
guards
151
what do guards do
- prevents multiple definitions (compilation errors) - handles circular dependencies - improves compilation efficiency
152
what are the 3 steps in the compilation process
1. preprocessing 2. compiling 3. linking
153
what happens in the preprocessing stage
handles #include, #define, etc
154
what happens in the compiling stage
translate .c files to object files (.o)
155
what happens in the linking stage
combine object files into executable
156
what is a Makefile
- build automation tool - a way to specify dependencies between files - method to avoid unnecessary recompilations
157
what do Makefiles require
tabs (NOT SPACES)
158
Makefile syntax
target: dependencies commands
159
example of a Makefile
hello: hello.c gcc hello.c -o hello
160
key features of using linked lists
- not contiguous in memory - can be anywhere there is space - no direct access - you must traverse the linked list - able to grow/shrink dynamically
161
code to print a linked list
void printList(const node *head){ const node* current = head; while (current->next != NULL){ printf("%.2f -> ", current->data); current = current ->next; } printf("%.2f -> ", current->data); }
162
recursive code to print a linked list
void printListRecursive( const node* head) { const node *current = head; if (current ->next) { printf("%.2f -> ", current->data); printListRecursive(current->next); } else { printf("%.2f -> ", current->data); } }
163
const
constant - not able to be edited - compiler error if you attempt to edit the values within the pointer