The C Family Flashcards
What does the term ‘imperative’ describe in programming?
Describes computation in terms of statements that change a program state
What is the opposite of imperative programming?
Declarative programming
What are the two main programming paradigms associated with C?
Procedural and functional
Is C a compiled or interpreted language?
Compiled
What type of typing does C use?
Statically, weakly typed
What does it mean for C to be statically typed?
Types are checked before runtime
What does weakly typed mean in the context of C?
Supports implicit type conversions
On what platforms is C available?
Pretty much every platform
What is a key characteristic of C regarding portability?
Very fast
What feature does C provide for memory management?
Explicit memory management
What standards does C adhere to?
ANSI/ISO standards
True or False: C has runtime error checking.
False
What type of error handling is lacking in C?
Sophisticated exception handling
What does GNU stand for?
GNU stands for ‘GNU’s Not Unix’
GNU is a free, UNIX-compatible operating system started by Richard Stallman in 1983.
What types of software packages does the GNU system include?
The GNU system includes various software packages, including:
* Compilers
* Libraries
* Tools
What is GCC?
GCC stands for GNU Compiler Collection, a powerful compiler that allows compiling different programming languages including:
* C
* C++
* Objective-C
* Fortran
* Java
* Ada
* Go
What command is used to compile a C program with GCC?
gcc myProgram.c
What is the default name of the executable file created by GCC?
a.out
How can you run the compiled program in Linux?
./a.out
How can you specify a custom output file name when compiling with GCC?
Use the -o option, e.g., gcc myProgram.c -o myProgram
What is the purpose of compiling to an object file?
Object files are portable and don’t need the full source code. They allow linking multiple object files to create a final executable.
What command is used to compile a C program into an object file?
gcc -c myProgram.c -o myProgram.o
What command is used to link an object file and create an executable?
gcc myProgram.o -o myProgram
What is the command to compile multiple source files at once?
gcc circle.c radius.c -o circle -lm
What does the -lm option do when compiling?
-lm links the math library, needed for functions like sqrt()
What is the first step in compiling multiple files separately before linking?
Compile each file separately using gcc -c
What is the command to link object files after compiling them separately?
gcc circle.o radius.o -o circle -lm
What is the solution to the error ‘sqrt not defined’?
Always link the math library using -lm.
What is the solution to the error ‘radius.o not found’?
Make sure all .o files are correctly compiled before linking.
What does K&R C refer to?
K&R C is the original version of C created by Kernighan & Ritchie.
What is ANSI C?
ANSI C (C89/C90) is the first standardized version of C, widely used.
What version of C was introduced in 1999?
C99
What is the latest update of the C language as of 2011?
C11
What is Embedded C?
Embedded C is a version designed for small systems (microcontrollers).
What integer value does a C program return to indicate success?
0
What does a C program return to indicate failure or error?
Any other number
Fill in the blank: When a C program finishes running, it returns an integer value to the _______.
operating system
Give an example of a return statement indicating success in a C program.
return 0;
What does ‘weakly typed’ mean in C?
C allows implicit type conversions, which can lead to unexpected results.
Example of implicit conversions can cause issues like data loss or overflow.
What is a potential issue when converting larger types to smaller types in C?
Data loss when converting larger types to smaller types.
This can occur when a larger data type is assigned to a smaller data type, resulting in truncation.
What is an example of signed int overflow in C?
When unsigned short int x = 65535; is assigned to short int y, y becomes -1.
This occurs because the maximum value of signed short int is 32767.
What is the output of printf for variable c when c = x; with x = 65535?
Undefined behaviour.
This happens because c is a char, which cannot hold the value 65535.
What are the two types of arrays in C?
1D arrays and 2D arrays.
Example: int numbers[5] = {1, 2, 3, 4, 5}; for 1D and int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; for 2D.
What does C not do with respect to arrays?
C does not perform bounds checking.
This can lead to accessing out-of-bounds elements, which can cause memory issues.
How are strings represented in C?
Strings are arrays of characters ending with a null terminator (0).
Example: char greeting[] = ‘Hello!’; automatically includes 0.
What does the function strlen(s) do in C?
Returns the length of the string (excluding the null terminator).
strlen counts the characters until it hits the null terminator.
What is the purpose of srand(seed) in C?
Sets a new seed to change the sequence of random numbers.
Using srand with time(0) ensures different sequences on each run.
What does the function rand() generate?
A pseudo-random integer between 0 and RAND_MAX.
RAND_MAX is a constant defined in stdlib.h.
What is the shape of the Normal (Gaussian) Distribution?
Follows a bell-curve shape.
This distribution is commonly used in statistics and natural phenomena.
What does the GNU Scientific Library (GSL) provide?
Better random number generators than rand().
GSL offers more sophisticated methods for generating random numbers.
What is the purpose of the function gsl_rng_set in GSL?
Sets the seed for the random number generator.
This is important for ensuring reproducibility of random sequences.
Fill in the blank: Strings in C are just arrays of characters ending with a ______.
null terminator.
The null terminator is represented as 0 in C.
True or False: C automatically checks for buffer overflows in arrays.
False.
C does not provide any built-in mechanism for bounds checking.
What is the output of printf when using sprintf(buffer, “%s %d”, str, num)?
Formats and stores output into buffer.
This allows for formatted strings to be stored for later use.
What is a one-dimensional array in C?
An array that holds a fixed number of elements of the same type, initialized with specific values
Example: Char array[5] = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
How can the size of an array be defined in C?
The size can be implicit and defined by its initialization
Example: Int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
What is an uninitialized array in C?
An array declared without an initial value, containing random data
Example: Int anArray[10];
How is a two-dimensional array initialized in C?
An array of arrays initialized with specific values
Example: Int a2[2][3] = { {1,2,3} , {4,5,6} };
How do you access and set individual values in an array?
Using the index notation, e.g., anArray[0] = 42 or array[3] = ‘Z’;
What is a string in C?
A string is an array of characters terminated by a null character (0)
Example: Char string[] = ‘Hello World!’;
What is the significance of the null terminator in strings?
It signals the end of the string to prevent the program from getting stuck.
True or False: Strings in C are enclosed in single quotes.
False
Strings use double quotes, while characters use single quotes.
What are functions in C?
Uniquely named groups of program statements that may accept parameters and return values.
What is the syntax for defining a function in C?
<return> functionName(<parameter>) { /* statements */ return <value>; }
</value></parameter></return>
What is the main function requirement in a C program?
Every program must include a main() function.
What is a procedure in C?
A function that does not return a value, defined with void.
What is the purpose of function prototypes?
To inform the compiler of the function’s signature before it is called.
What is the difference between global and local scope?
Global scope variables are declared outside functions, while local scope variables exist only within the function.
What are static variables in C?
Variables that are initialized only once and retain their value between function calls.
Fill in the blank: Functions must have a _______ name.
unique
What should be avoided unless necessary in function design?
Using global variables.
What are the key points regarding functions in C?
- Define using a clear structure and unique names
- Avoid overloading; separate by purpose and return type
- Use prototypes to declare functions before use
- Avoid global variables unless justified
- Utilize static variables for data persistence
What fundamentals were covered in this lecture?
Defining and using functions, role of prototypes, scope, and static variables.
What is stored in memory?
Every variable
Memory is a linear array of bytes.
What does each memory location have?
An address (a numerical label)
This address is used to identify the location of the variable in memory.
How many bytes are typically allocated for an integer variable?
4 bytes
This is common on many systems.
What is a pointer?
A variable that stores a memory address instead of a value.
How do you declare a pointer to a character?
char *p;
This declares p as a pointer to a character.
What does the & operator do?
Gives the address of a variable.
What does the * operator do?
Dereferences a pointer to access the value at the stored memory address.
What is pointer arithmetic?
Performing arithmetic operations on pointers.
Fill in the blank: A void pointer (void *) is a _______.
Generic pointer that can store addresses of any data type.
What function is used for dynamic memory allocation?
malloc()
What should you always check after using malloc()?
If malloc() succeeds.
What function is used to release allocated memory?
free()
What are common pitfalls related to pointers?
- Memory Leaks
- Dangling Pointers
- Wild Pointers
What is a segmentation fault?
Occurs when trying to access memory illegally.
What tool can be used for memory debugging?
valgrind
True or False: Pointer arithmetic follows the size of the data type.
True
What happens if you forget to free memory?
Memory Leaks occur.
What is a dangling pointer?
Using a pointer after the memory it points to has been freed.
What is a wild pointer?
Using uninitialized pointers.
What does p++ do if p is a pointer to an int?
Moves p to the next int (increases by sizeof(int)).
What happens when you write beyond allocated space?
It can corrupt adjacent memory.
What is the output of printf(“p = %p, *p = %c\n”, p, *p) if p points to ‘A’?
p= 0x1e224eff, *p= A
Fill in the blank: The function _______ is used to allocate memory for an array of integers.
malloc()
What is Pass by Value?
A copy of the variable is passed to the function, keeping the original variable unchanged.
Default in C; can be inefficient for large data structures.
What is a downside of Pass by Value?
Can be inefficient for large data structures.
It involves copying the entire data, which takes extra memory and processing time.
How does Pass by Reference work?
A pointer to the variable is passed instead of a copy, allowing the original variable to be modified.
Great for modifying large data structures efficiently.
What is a pointer in C?
A pointer stores the memory address of another variable.
Syntax example: int *p = &x; where p stores the address of x.
What is the syntax to dereference a pointer?
Using the asterisk (*) before the pointer variable.
Example: printf(“%d”, *p); prints the value at the address stored in p.
What is a function pointer?
A function pointer stores the address of a function.
Syntax example: int (*funcPtr)(int, int); for a function taking two ints and returning an int.
Why use function pointers?
Makes code modular and reusable; enables dynamic function execution.
Useful in scenarios like callbacks and sorting.
What is a key advantage of linked lists over arrays?
They do not need a predefined size and allow efficient insertions and deletions.
This makes linked lists more flexible for dynamic data storage.
What is the basic structure of a linked list node?
struct Node { int data; struct Node *next; };
Each node contains data and a pointer to the next node.
How do you insert a node at the beginning of a linked list?
Create a new node, set its next to the current head, and update the head to the new node.
Example: void insert(struct Node** head, int newData) {…}
What is the purpose of the printList function?
To traverse and print all the nodes in the linked list.
Example: void printList(struct Node *node) {…}
True or False: Pass by reference allows modifying original values.
True.
This is done by passing pointers to the function.
Fill in the blank: _______ enables dynamic execution of functions.
Function pointers.
They allow the program to choose which function to execute at runtime.
Final takeaway: What do linked lists provide compared to arrays?
More flexibility for dynamic data storage.
Linked lists can grow and shrink in size easily compared to static arrays.
What is the purpose of scanf() in C?
Takes user input
It is like the reverse of printf()
What does scanf() return?
Number of values successfully assigned
What happens if input fails in scanf()?
Exits the loop
Define a stream in the context of programming.
A way of handling data flow in a program
What are the key features of a stream?
- Abstracts file handling
- Buffered
- Two Types: Text Streams and Binary Streams
What is the function to open a file in C?
fopen()
What is the function to close a file in C?
fclose()
What does a file pointer (FILE *) do?
Accesses files in C
What does fopen() return if it fails?
NULL
What mode is used to open a text file for reading?
r
Fill in the blank: To create a binary file for writing, use mode _______.
wb
What is the action of the function fputs()?
Write a string
What does fprintf() do?
Writes to a file like printf()
What is the purpose of the function fseek()?
Jump to a specific position in a file
What is the role of errno in error handling?
Global variable to check errors
What are the three standard streams in C?
- stdin
- stdout
- stderr
What does stdout represent?
Standard output (console)
What is the result of the command ‘./myprogram > output.txt 2> errors.txt’?
Saves stdout in output.txt and stderr in errors.txt
What happens when you reach the end of a file (EOF)?
Stops reading
What is the summary takeaway regarding file operations?
Always check if fopen() worked before reading/writing
True or False: The function remove() is used to delete a file.
True
What is the C Preprocessor?
Before your code is compiled, it passes through a preprocessor that expands macros and header files, removes comments, allows conditional compilation, and modifies source code before sending it to the compiler.
What does the directive #include <file> do?</file>
Includes a system header file.
What does the directive #include “file” do?
Includes a user-defined header file.
What is the purpose of #define MACRO?
Defines a macro (a shortcut for values or code).
What happens when #ifdef MACRO is used?
Compiles code only if a macro is defined.
What does #ifndef MACRO do?
Compiles code only if a macro is NOT defined.
What is the function of #undef MACRO?
Undefines a macro.
What does the #pragma directive provide?
Compiler-specific instructions (rarely used).
What are system headers and how are they included?
System headers are included using angle brackets < >, e.g., #include <stdio.h>.</stdio.h>
What are user-defined headers and how are they included?
User-defined headers are included using quotes “ “, e.g., #include “myfile.h”.
What does #define PI 3.14159 accomplish?
Replaces every PI in the code with 3.14159.
What is a common pitfall when using macros?
Not using parentheses can lead to unexpected results.
How can the MAX macro be defined correctly?
define MAX(a, b) ((a) > (b) ? (a) : (b))
What does stringifying macros do?
Converts macro arguments into strings.
What is the benefit of structuring code?
Makes code easier to read, allows reusability, and improves debugging and maintainability.
What are the components of a structured project?
- myProgram.c (Main Program)
- myProgram.h (Header File)
- stack.c (Stack Implementation)
- stack.h (Stack Function Declarations)
What do header files contain?
Function declarations and constants.
What do source files contain?
Function definitions.
What is the purpose of #ifndef STACK_H?
Prevents multiple inclusions (aka include guards).
What are the three stages of compilation?
- Preprocessing
- Compilation
- Linking
What command compiles source files separately?
gcc -c stack.c -o stack.o
What is the command to link object files?
gcc stack.o myProgram.o -o myProgram
What is the purpose of a Makefile?
Saves time when recompiling large projects, automatically tracks dependencies, and reduces manual errors.
What command is used to build a project using a Makefile?
make
What is a library in C?
A collection of precompiled functions that can be used in multiple projects.
What is the difference between a static library and a shared library?
- Static Library (.a): Linked at compile time (larger executable)
- Shared Library (.so): Linked at runtime (smaller executable)
What command links the math library?
gcc myMaths.c -lm -o myMaths
What does the -lm flag do?
Tells GCC to link the math library.
What does the preprocessor do?
Expands macros, includes headers, and modifies code.
What should you do to prevent errors when using #define?
Use #define wisely.
What is important to remember about structuring code?
Structure code into multiple files (.c and .h).
What is the benefit of using Makefiles?
Automate compilation.
Fill in the blank: A library is a collection of _______.
[precompiled functions]