Basics of C Programming Language Flashcards
What are the 3 general steps in creating an executable?
- Preprocessing
- Compiling
- Linking
What is preprocessing?
Before code is compiled it is given to a program called the preprocessor. The preprocessor edits and manipulates code, setting it up for the compiler. Typically the preprocessor looks for lines that begin with # and alters the code based on these directives.
What is compiling?
Preprocessed code is given to the compiler, a program that translates C statements into machine instructions.
What is linking?
A linker combines the object code produced by the compiler with any additional code needed to create a complete execuatable. This additional code includes things like library functions.
What are the three fundamental language features that C relies on?
- Directives
- Fucntions
- Statements
What is a function?
A series of statements grouped together and given a name
What does main return?
An integer status code
What is a statement?
A command to be executed when the program runs.
Definition: String literal
A sequence of characters surrounded by “”
What are the valid ways to write comments in C?
/* this is the only valid comment */
some compilers allow // but it is not part of standard C
Definition: variable
A data storage location
What is a variable’s type?
A specification of what type of data it will hold
Definition: expression
a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces (returns, in a stateful environment) another value.
True/False: An expression of the same type can be substituted wherever a value is needed.
True
Definition: format string
A string literal which specifies a method for rendering an arbitrary number of varied data type parameter(s) into a string
Definition: constant
A value that doesn’t change during execution
Definition: Identifier
A symbol that represents an entity such as variables, functions, and macros.
Definition: token
A group of characters that can’t be broken up without changing their meaning
Definition: conversion specification
A placeholder, preceded by a %, representing a value to be filled in during printed. The value following the % specifies how the value is convereted from internal form to printed form
What forms can a conversion specification have? What do the values mean?
%m.pX or %-m.pX m: minimum field width p: precision X: conversion specifier -: left align
What does p specify when used with %m.pd?
What if p is bigger than the length of the value to be printed?
Minimum number of digits. Output is zero-filled
What is the conversion specifier: d
decimal integer
What is the conversion specifier: e
floating point in exponential form
What does p indicate in %m.pe? What if p == 0?
How many digits appear after the decimal. The decimal is not displayed
What is the conversion specifier: f
Floating point in fixed-decimal format
What is the meaning of p in %m.pf? What if p == 0?
Number of digits after the decimal. Decimal is not shown
What is the conversion specifier: g
Floating point in either exponential or fixed decimal format depending on the number of significant digits.
Whats the difference between %f and %g when displaying data in fixed decimal format?
%g won’t show trailing zeros
How does scanf work?
Starts at the left of the format string. For each conversion specification it tries to locate an item of the appropriate type, skipping blank spaces if necessary. It reads until it finds a character that cannot be part of the string which it puts back into the buffer.
What happens if scanf cannot read an item successfully?
scanf returns immediately without looking at the rest of the format string or remaining buffer data.
What does scanf look for when reading an integer?
First: a digit or minus sign
Reads until a nondigit
What does scanf look for when reading a floating point?
- a plus or minus sign (optional)
- a sequence of digits possibly containing a decimal point
- an exponent (optional) consisting of the letter e, and optional sign, and one or more digits
What does scanf do when it encounters a whitespace character?
One whitespace character in the format string will match any number of whitespace characters in the input
What does scanf do if it encounters a non-white-space character in a format string?
It compares it with the next input character? If the two match, then the non-white-space character is discarded and scanf continues processing the input string. If they do not match, scanf puts the character back in the buffer and aborts.
Definition: arithmetic operators
Operators that perform some mathematical functions (+, -, *, /, %)
What is the precedence for arithmetic operators?
unary +, unary -, *, /, %, +, -
What is operator associativity?
When dealing with multiple operators, precedence is not enough to determine order of operations. Associativity comes into play when an expression contains multiple operators of the same level of precedence, and determines which operation will be evaluated first.
What is a left associative operator?
An operator that groups from left to right. Ex: i - j - k == (i -j) - k
Which arithmetic operators are left associative?
binary +, binary -, *, /, %
What is right associativity?
An operator that groups from right to left.. ex: -+x == -(+x)
Which arithmetic operators are right associative?
unary +, unary -
Definition: lvalue
Lvalues are values that have addresses being programmatically accessible to the running program. They are variables or dereferenced references
Definition: compound assignment
An assignment that uses the old value as part of the computation for the new value. Ex += *= …
What is a logical expression?
An expression that results in true or false (nonzero or 0)
What are relational operators?
A binary operator that tests a relationship between two entities and produces true or false:
, <=, >=
What is an equality operator?
A binary operator that tests equality or lack of equality between two entities:
!=
What associativity do relational and equality operators have in C?
left
What are the C logical operators? What do they produce? How do they evaluate operands?
!, &&, ||
They produce a 1 (true) or a 0 (false)
They evaluate any non-zero as true and 0 as false
What is a logical short circuit? Which operators perform this?
In something of the form: expr1 && expr2,
if expr1 is 0, expr2 is not evaluated and 0 is returned.
In an expression of the form:
expr1 || expr2, if expr1 is non-zero, expr2 is not evaluated and 1 is returned
What is the associativity of the logical operators?
! is right associative
&&, || or left associative
What is a compound statement?
A group of statements enclosed by {}, indicating to the compiler that the group is to be treated as a single statement
What is the rule for determining which if statement an else belongs to?
An else is paired with the nearest unpaired if statement
What is a conditional expression? What is the conditional operator in C?
Conditional expression is a compound expression that chooses between two expressions based on the truth value of the first one. evalExpr is evaluated, if its value is non-zero, trueExpr is evaluated and its result is the result of the entire expression. Viceversa for falseExpr.
evalExpr ? trueExpr : falseExpr ;
What is a controlling expression
An expression that is evaluated at some point during each iteration and determines if the loop will continue (expr != 0) or if it will discontinue(expr == 0)
What is the comma operator?
expr1, expr2
expr1 is evaluated and its result is dicarded. Then expr2 is evaluated and its value and type is returned.
How does the break statement work?
When executed, it transfers control just past the end of innermost loop or switch
How does the continue statement work?
When executed, it transfers control to just before the end of the loop
What is a null statement? What is it good for?
An empty statement -just a ;
It’s useful for creating a loop body that does nothing.
What are the two categories of integers?
Signed (default) and unsigned
What are the six combinations of modifiers with int?
short int unsigned short int int unsigned int long int unsigned long int
What is a heuristic for choosing modifiers with int to improve portability?
For values between -32,768 and 32,767, use int. For all other values use long int
What is an integer constant?
A number that appears in the text of the program.
ex:
10, xABC, 017
How are decimal, octal, and hexadecimal constants differentiated?
Decimal - contain digits 0-9 and do not start with a 0
Octal - contain 0-7 and start with a 0
Hex - contain 0-9 and a-f and start with a 0x
How do you force the compiler to treat a an integer constant as long? Unsigned?
Follow it with L. Follow it with U.
ex: 15UL == 15ul == 15LU == 15lu
What is the conversion specifier for reading/writing an unsigned decimal? unsigned octal? unsigned hex?
What if we want the short or long versions?
decimal: %u
octal: %o
hex: %x
short: %h[u,o,x,d]
long: %l[u,o,x,d]
What is the default type for floating point constants?
double
What are the conversion specifications for single precision floating point values? Double precision? Long double?
single: %f, %g, %e
double: %lf, %lg, %le
long double: %Lf, %Lg, %Le
When should you use l in conjunction with a floating point conversion specification?
Only with scanf. printf %[e,f,g] can print single and double precision
How does C treat chars?
8 bit integers. The C specification does not specify whether they are signed or unsigned.
What is the conversion specifier for characters?
%c
What functions can you for characters instead of scanf and printf?
getchar() and putchar(char ch)
What is the sizeof operator?
Allows a program to determine how much memory is required by a particular type
What considerations are there when printing a sizeof value?
The return type is implementation defined. The trick is cast it to a known type before printing.
What is the difference between the two types of conversions in C?
Implicit conversions are performed automatically by the compiler. Explicit conversions are mandated by the programmer.
When is implicit conversion performed? (4)
- the operands in an arithmetic or logical expression do not match
- the type of the right side of an assignment doesn’t match the type of the lvalue
- the type of an argument of a function doesn’t match the type of the corresponding parameter
- the expression in a return statement doesn’t match the function’s return type
What is usual arithmetic conversion?
When binary operators have mixed types, their values are converted to the narrowest type that will accommodate both values. The narrowest type is the one that requires the least number of bytes to store.
What is integral promotion?
When an integer type is converted to a less narrow integer type. If a short int is added to a long int, the short int is promoted to long.
When does integral promotion occur?
Whenever the compiler says it should occur:
Logically: when operating with mixed integer types. ex: int + long.. int is promoted to long
Also: short a = 1; short b = 2; a += 2; Will throw a warning because C specification says += returns an int and we are trying to store an int in a short.
What are the two cases for usual arithmetic conversions?
- The type of either operand is a floating type
2. Neither operand has a floating type
What is the promotion chart for floating point types?
long double ^ double ^ float
What is the promotion chart for integers?
unsigned long int ^ long int ^ unsigned int ^ int
What happens when an unsigned integer is mixed with a signed operand?
Signed operand will be treated as unsigned. The sign bit of the signed operand will be treated a normal bit and produce unexpected results. ex:
signed int i = -10;
unsigned int j = 10;
printf(“%d\n”, (i < j));
will print 0 instead of 1
What conversion happens in an assignment statement?
If the rvalue type is different from the lvalue type, the rvalue type is converted to the value type
How do you cast?
( cast-to-type ) expression
What is the purpose of typedef? How do you typedef?
To give alternate names to existing types.
typdef existing-type symbol
Why not just use macros instead of typedefs?
Type definitions are more powerful. Array and pointer types cannot be defined as macros. Typedef names are subject to the same scope rules as variables. Macros are not and cause unexpected errors.
Definition: array
A data structure containing a number of data values, all of which have the same type.
What is needed to declare an array?
- a type
- an identifier
- the size of the array enclosed in brackets OR empty brackets with an initializer
What is an array initializer?
a list of constant expressions enclosed in {} and separated by commas
How are multidimensional arrays stored in memory?
Row major order. Row 1 is ascending index order, then row 2, so on and so on.
What is a constant array?
An array declared const cannot be modified.
What is the assumed return type of a function that does not specify its return type?
int
What is a function prototype?
A way to provide the compiler the way to call a function before we implement it.
What is the difference between parameters and arguments?
Parameters appear in function definitions. They are dummy names for the values passed in the function call.
Arguments are expressions that appear in function calls.
Arguments supply parameters their value.
What does “pass by value mean”?
In each function call, the evaluated argument’s value is assigned to the corresponding parameter
What is main the implication of pass by value?
Changes made to the parameter does not affect the value of the argument.
How can you write a function that changes values?
Define a function that takes pointers to the values you want to alter.
What does the compiler do if it encounters arguments that don’t match the types of the parameters?
Case 1:
The compiler has seen a prototype for the function - The value of each argument is implicitly converted to the corresponding parameter’s type
Case 2:
The compiler has not seen a prototype for the function - The compiler performs default argument conversion. Floats are promoted to doubles, integral promotions are performed (char/short to int)
What happens when an array is passed to a function?
The function is given a pointer to the first element of the array.
What is the value that main returns?
A status code to the operating system
What is the difference between return and exit?
Exit can be called from any function
What is a local variable?
A variable only accessible in the block in which it is defined. Typically inside a function
What are the default properties of a local variable?
Automatic storage duration
Block scope
What is storage duration?
The portion of program execution during which storage for the variable exists.
What is automatic storage duration?
Storage for an auto variable is allocated when the program flow enters its block and is deallocated when flow leaves its block
What is scope?
The portion of the program text in which a variable can be referenced.
What is block scope?
A variable with block scope is only visible from its point of declaration to the end of its block
What is a static variable?
A variable with static storage duration has a permanent storage location. It retains its value throughout the execution of the program.
What properties do parameters have?
Same as local variables:
automatic storage duration and block scope
What properties do global variables have?
Static storage duration
File scope
What is file scope?
A variable with file scope is visible from the point of its declaration until the end of the file
What is a block?
A compound statement that contains declarations
What happens when a variable is declared inside a block that has the same identifier as a variable outside the block?
The new declaration hides the old one for the duration of the block
What is a reference type?
Every pointer needs a reference type, or rather, a type that the pointer points to
What two operators does C provide to work with pointers?
& - the address of operator, returns the location in memory of its operand
- the indirection operator, “follows the pointer” to its value
How do you prevent a function from changing the value of variable whose pointer was passed to the function?
Declare the parameter to be const
What three forms of pointer arithmetic does C support?
- Adding an integer to pointer
- Subtracting an integer from a pointer
- Subtracting two pointers
What does subtracting array pointers yield?
The number of elements between the pointers
What is the meaning of the expression:
*p++
value of expression is *p, increment p later
What is the meaning of the expression:
(*p)++
value of expression is *p, increment *p later
What is the meaning of the expression:
*++p
increment p, value of expression is *p
What is the meaning of the expression:
++*p
increment *p first, value of expression is *p
How would you rewrite a[3] = j using pointers?
*(a + 3) = j
What is the difference between using the array name and a pointer to the array?
You cannot assign a new value to the array name. Additionally, int a[10] sets aside 10 memory locations, int *a does not.
Why is a[i] equivalent to i[a]
The compiler treats a[i] as *(a + i) which is the same as *(i + a)
What is a string literal?
A sequence of characters enclosed in “”
Why are we allowed to use a string literal whenever a char * is required?
C treats string literals as character arrays.
What is the conversion specification to print or read a string?
%m.ps
m: minimum field width
p: print the first p characters
s: string
Why do you not need to put a & in front of a string variable in scanf(“%s”, str)?
str is a character array, thus str is treated a pointer automatically
What is important to remember about inputting strings with scanf?
A string read using scanf will never contain white-space
What function should you use to read an entire line of text?
gets doesn’t skip whitespace, it stops reading when it sees a \n (does not include \n)gets doesn’t skip whitespace, it stops reading when it sees a \n (does not include \n)
What is a ragged array?
An array whose rows are different lengths.
Considering command-line arguments: what is stored at argv[argc]?
A null pointer
Why is char *argv[] equivalent to char **argv for command line arguments?
The arguments are string literals. You reference string literals by pointers to their first character. If you have many arguments, then you need an array of character pointers to access them. C treats array names and pointers in parameters the exact same.
What is the preprocessor?
A program that sets up the source code for the compiler
What is a macro?
The #define preprocessor directive creates macros - names that represent something else. The preprocessor will expand these macros during preprocessing
What are the 6 preprocessor conditional directives?
if, #ifdef, #ifndef, #elif, #else, #endif
What are the 5 predefined macros?
\_\_LINE\_\_ \_\_FILE\_\_ \_\_DATE\_\_ \_\_TIME\_\_ \_\_STDC\_\_
What is the #ifdef identifier operator equivalent to?
if defined(identifier)
What is the #error directive?
Indicates a serious flaw in the program and causes most compilers to stop compiling. It prints the message associated with the directive
What does the keyword extern do in conjunction with a variable declaration?
Informs the compiler that the variable is defined elsewhere and there is no need to allocate space for it.
How do you protect a header file from being included multiple times?
endif
Enclose its contents in a #ifndef-#endif block. For example: a header file named stack.h:
#ifndef STACK_H #define STACK_H
stuff
When are header files compiled?
They aren’t. Their contents are compiled along with the file that includes them
What does the linker do?
The linker combines object files created by the compiler into an executable image. The linker is responsible for resolving external references left behind by the compiler from function calls to other files and references to external variables.
What is a makefile?
A file containing the necessary information to build a program. It lists the files and describes their dependencies.
What is the format of a make file entry?
target : dependencies
command
example:
fmt : fmt.o word.o line.o
gcc -o fmt fmt.o word.o line.o
How does the makefile know which files to recompile during a rebuild?
It checks the timestamps of the files to determine which are out of date.
What is the primary difference between an array and a structure?
Structures can be composed of different types
What is the primary difference between structs and unions?
Members of structs are stored at different memory locations, members of unions are stored at the same address.
What is a namespace?
A container that provides context for the identifiers it holds, and allows for the disambiguation of homonym identifiers in different namespaces.
How do we access a member of a struct?
identifier.member
Are members of structs lvalues or rvalues?
lvalues
How do you create a copy of struct?
structVar1 = structVar2
assuming they are the same type
How do we define and use a structure tag?
define: struct identifier{ stuff };
use: struct identifier ..
How we do define a type name for a struct?
typedef struct identifier{stuff} Typename;
What is the downside to passing a structure to a function or returning a structure from a function? What is a logical improvement to this paradigm?
The stack frame must allocate space for the structure which can be costly if the structure is large. By passing or returning pointers we can improve performance.
What is one of the primary uses of unions?
They can be used to save space in structures when mutually exclusive members exist.
What is one of the major problems inherent with using unions? How do we rectify it?
There is no way to tell which member of the union was last changed, and therefore contains a meaningful value. The simplest solution is embed a union in a struct where the struct has a tag field indicating which member was last changed.
What is an enumeration?
A type whose values are listed and named.
What is one of the main functional differences between enumerations and #define constants
enumerations are subject to C’s scope rules
What are the 3 ways to define enumerations?
enum identifier {…};
typedef enum {…} identifier;
typedef enum tag {…}identifer;
How could you use enum to create a Boolean type?
typedef enum{FALSE, TRUE} Boolean;
How do you alter the values associated with each constant in an enumeration?
typedef enum{CONST1 = …}identifier;
What is dynamic memory allocation? Where is this memory allocated from.
The allocation of memory storage for use during the runtime of that program. Its allocated from the heap (usually)
What is one of the primary benefits of dynamic memory allocation?
We can create data structures that grow and shrink during execution
What are the three dynamic memory allocation functions and what header are they declared in?
malloc() calloc() realloc()
What is the difference between malloc and calloc?
malloc allocates a block of memory but doesn’t initialize it. calloc allocates a block of memory and clears it
What does realloc do?
Resizes a previously allocated block of memory
What do malloc, calloc, and realloc return? What if the memory couldn’t be allocated?
void *
a generic memory pointer
if it couldn’t allocate the memory -it returns a null pointer
What is crucial to do when using memory allocation functions?
Check to see if the value returned is a null pointer.
If p is of type char *, why is it not necessary to cast the void * in
p = malloc(sizeof(“stuff”));
There is an implicit conversion when a variable of one type is assigned a variable of another type.
How would we use malloc to allocate space for an array of n struct a’s?
struct a *arr = malloc(n * sizeof(struct a));
How is calloc used?
void *calloc(size_t nelem, size_t size)
returns a generic pointer to a zeroed block of memory large enough for nelem number of elements each of size length
How is realloc used?
void *realloc(void *ptr, size_t size)
returns a generic pointer to a block of memory previously allocated by a memory allocation function identified by ptr and resized to size
What is garbage? How does it relate to memory leak? How do we handle this?
Garbage is memory that no longer has a pointer to it and therefore can no longer be referenced. Programs that have this scenario have a memory leak. C does not have a garbage collector so we are responsible for freeing memory blocks that are no longer needed.
How is free used?
void free(void *ptr) frees the memory identified by ptr. ptr must point to a block that has been previously allocated by a memory allocation function
What is the dangling pointer problem?
When a dynamically allocated block is freed, the pointer still exists but does not point to anything. Attempting to use the pointer again can cause bugs.
What is important to remember when a structure has a member that is a pointer to said structure?
We are required to use a structure tag, and cannot use a type definition.
What is a linked list?
A data structure that has a data part and a pointer to the next node in the list.
What is the process of creating a node?
- allocate memory for the node
- store the data in the node
- insert the node into the list
How can you use malloc to create a node?
struct node *newNode = malloc(sizeof(struct node));
What is the right arrow selection operator?
->
it is equivalent to (*identifier).element
What are the three steps in deleting a node from a linked list?
- find the node
- make the node before the node to be deleted point to the node after the node to be deleted
- free the memory for the deleted node
How do you create a function pointer?
return-type (id)(parameter-type, ..);
ex:
void (pf)(int)
a function pointer to any function that returns void and takes a single int
How do you use a function pointer?
1. define a function pointer void (*fp)(int) 2. assign it a function fp = func; (correct form is use &func, but its not necessary) 3. call the function fp(10); you can use (*fp)(10)
What the difference between a declaration and a definition?
A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier.
A definition actually instantiates/implements this identifier. It’s what the linker needs in order to link references to those entities.
What is the general form for declarations?
declaration-specifiers declarators;
What are declaration specifiers? What 3 categories do they fall into?
Declaration specifiers describe the properties of of the items being declared.
They fall into three categories:
storage classes
type qualifiers
type specifiers
What are the 4 storage classes? What is the restriction placed on their combination?
auto, static, extern, register
at most one may appear in a declaration
What are the 2 type qualifiers? What is the restriction placed on their combination?
const, volatile
any combination may appear in a declaration
What are the type specifiers?
void, char, short, int, long, float, double, signed, unsigned, struct, union, enum
What are declarators?
In short: identifiers
variable names, array names, pointer names, function names, etc.
What is the storage duration, scope, and linkage of: a variable declared inside a function
auto
block
none
What is the storage duration, scope, and linkage of: variables declared outside any block
static
file
external
What is the storage duration, scope, and linkage of: a static variable declared outside any block
static
file
internal
What is the storage duration, scope, and linkage of: a static variable declared inside a block
static
block
none
What does the extern storage class enable?
The sharing of the same variable between files
What does putting extern in front of a variable do?
Indicates to the compiler that the variable is defined somewhere else in the program, and space should not be allocated for it.
What storage class do extern variables always have?
static
What determines an extern variables scope?
The placement of its declaration. Inside a block means block scope, otherwise file scope.
What does declaring a variable to have the storage class register mean?
It requests a variable be stored in a cpu register.
Where is the only legal place for a register variable to be declared?
In a block
What is the storage storage duration, scope, and linkage of a register variable?
Same as an auto variable.
auto
block
no linkage
What is a crucial difference between an auto variable and a register variable?
You cannot use & with a register variable
Why would you use the register storage class?
Because registers are accessed more quickly than memory, you can use them for variables that are accessed/changed frequently like loop counters
What does extern indicate in conjunction with function declarations/definitions?
It specifies that the function has external linkage, allowing it to be called from other files.
What does static in conjunction with function declarations/definitions mean?
Specifies the function has internal linkage -the function may be called only within the file in which it is defined.
What storage class is assumed for functions if no storage class is defined?
extern, and thus specifying a function to be extern is redundant
What is the type qualifer const used for?
To declare objects that are read-only
What does the volatile type qualifer indicate?
It tells the compiler that the value of the variable may change at any time–without any action being taken by the code the compiler finds nearby. This has implications especially when dealing with compiler optimization
What is the rule of thumb for deciphering complex declarations?
- Read from the inside out - find the identifier and start from there
- When there is a choice, favor [] and () over * - if the identifier is *id[] it is an array of pointers not a pointer to an array
What is the restriction on initializers for static variables?
The initializer must be constant
What exactly is the difference between “scope” and “linkage”?
Scope is for the benefit of the compiler, while linkage i for the benefit of the linker. The compiler uses the scope of an identifier to determine whether or not it’s legal to refer to the identifier at a given point in a file. When the compiler translates a source file into object code, it notes which names have external linkage, eventually storing these names in a table inside the object file. Thus, the linker has access to names with external linkage; names with internal linkage or no linkage are invisible to the linker.
Why can’t const objects be used in constant expressions?
A const object is only guaranteed to stay constant during its lifetime, not throughout the execution of the program.
What is a module?
A collection of services, some of which are made available to other parts of the program (clients)
What is a module interface?
A common means for two unrelated modules to interact.
What are the two properties that modules should have?
High cohesion, and low coupling
What is cohesion?
The extent to which elements of a module are related.
What is coupling?
The extent to which modules are dependent on each other.
What are the 4 bitwise operators from highest precedence to lowest precedence?
~
&
|
How do you set a bit in a bit string?
Do a bit wise or with a zeroed string but with a 1 in the position of the bit you want to set
How do you clear a bit?
Do a bitwise and with a string with all 1’s but with a zero in the position you want to clear
How do you flip a bit?
Do a bitwise XOR with a zeroed string with a 1 in the position you want to flip
How can you use bitshifts to create a bit mask?
If you want a 1 in position j you would do:
i = (1 «_space;j)
If you want a zero in position j:
i = ~(1 «_space;j)
How do you declare a structure whose members represent bit fields?
struct identifier{
(unsigned) int: #ofbit
};
unsigned is optional
Why would we need a type qualifier such as volatile?
If we have a pointer to a volatile memory location, the data at that location can change without program interference. If we write a program that has a pointer to that location and we are continually checking it -the compiler might recognise that we aren’t changing the pointer or the pointee and optimize the code by fetching the value once and storing it in a register. This would not be what we want because we would only have the value of the volatile memory address at a specific point in time, and not as it continuously changes.
What is a stream in C?
Any source of input or any destination for output
How are streams accessed in C?
Through file pointers… FILE *fp
What are the 3 ready-to-use streams provided by stdio.h
stdin - keyboard
stdout - screen
stderr - screen
What are the two types of files supported by stdio.h? What is the difference between them?
Text files - Bytes represent characters, making it human-readable
Binary files - Bytes represent other types of data.. ints, floats, etc
What are the 6 mode strings? How do you make a mode string for a binary file?
r - reading
w - writing (file need not exist)
a - appending (file need not exist)
r+ - reading and writing starting at beginning
w+ - reading and writing (truncate if exists)
a+ - reading and writing (append if exists)
To make a binary mode string, add b to the mode strings listed above.
What does freopen do? What is its most common use?
Attaches a different file to a stream that’s already open. Its most common use is to associate a file with one of the standard streams.
What is freopen’s normal return value?
It’s third argument, a file pointer to a stream like stdout.
What does tmpfile from do?
Returns a pointer to a file that will remain open until its closed or until the program ends.
How does output buffering work?
Data to be stored is written to a buffer. When the buffer is full or the stream is closed, the buffer is flushed (written to device).
How does input buffering work?
Input is put into an input buffer, and input is read from this buffer as opposed to reading from the actual device.
What does fflush do? What arguments does it take? What does it return?
Flushes a file’s buffer.
Takes a file pointer or NULL, NULL flushes all buffers.
If it is successful, it returns 0. If there is an error it returns EOF.
What is setvbuf used for?
Allows us to change the way a stream is buffered and to control the size and location of the buffer.
What is full buffering?
characters are transmitted to the system as a block when a buffer is filled
What is line buffering?
characters are transmitted to the system as a block when a new-line character is encountered. Line buffering is meaningful only for text streams and UNIX file system files.
What is no buffering?
characters are transmitted to the system as they are written. Only regular memory files and UNIX file system files support the no buffering mode.
What is the benefit of creating a buffer with automatic storage duration? What is the benefit of using a dynamically allocated buffer?
Using an automatic variable allows space to be reclaimed automatically at the end of the block.
Using dynamically allocated space allows us to reclaim the space when we no longer need the buffer.
What is the restriction placed on using setvbuf
It must be called after the stream has been opened but before any other operations are performed on it.
What is assert used for?
Allows a program to monitor its own behavior and detect possible programs at an early stage.
What is an assertion>
An expression that we expect to be true under normal circumstances.
How does assert work?
It takes an integer argument(an assertion) that it tests when it executes. If the argument in non-zero: assert does nothing. If it is zero assert prints a message to stderr and calls the abort function to terminate the program.
How do you disable assert using 1 line of code?
Define the macro NDEBUG prior to including
#define NDEBUG #include
What is the errno variable? What header is it declared in?
Some functions indicate failure by storing an error code in the errno variable.
errno is defined in
What is important to remember when checking if a function has altered errno?
You must clear errno before using a function that might change errno. If an error code has been stored in errno prior to calling a function, and the recent function does not return an error code, errno will retain the previous error code. Library functions do not clear errno.
What does the signal.h header do?
provides facilities for handling exceptional conditions, known as signals
What are the two categories that signals fall into?
Run-time errors
External events
What does it mean that signals can happen asynchronously?
Signals can be raised at any time during program execution, not just at certain points known to the programmer.
What does the signal function do?
Installs a signal handling function for use later if a given signal should occur.
What are the two parameters to the signal function?
The first is the code for a particular signal (usually a macro)
The second is a function pointer to a function that will handle the signal
What argument must every signal handling function be passed?
An int for the signal code that will be passed to the handler.
What happens if the signal handling function returns?
Execution resumes from the point where the signal occurred.
What are the two predefined signal handlers provided by signal.h?
SIG_DFL : the default handler -usually causes program termination
SIG_IGN : specifies the signal code should be ignored should it arise
What is the SIG_ERR macro used for?
It’s used to test whether a signal handler can be installed. If it can’t signal returns SIG_ERR and stores a positive value in errno.
What prevents infinite recursion if the function handler raises a signal?
C requires that when a handler is called for signals other than SIGILL, the handler be reset to SIG_DFL or blocked in some other way.
What has to happen in order for a signal to be handled twice by the same handler?
The signal handler has to be reinstalled. This can be done at the end of the handler’s block.
What does the raise function do? What is its argument? What does it return?
raises causes a signal to occur
its argument is the signal code to be raised
its return value is 0 for success, nonzero for failure
What does the setjmp.h header do?
Makes it possible for one function to jump directly to another function without returning. It’s primarily used for error handling
What does the setjmp.h header do?
Makes it possible for one function to jump directly to another function without returning.
What does the setjmp function do? How do we use it? What does the longjmp function do? How do we use it?
setjmp marks a place in a program so we can jump to it later from longjmp. We pass setjmp a variable of type jmp_buf, it then returns 0. longjmp returns to the point where we used setjmp. we use it by passing it the jmp_buf variable we used with setjmp and another int value for the status code.
What does the float.h header provide?
Macros that define the range and accuracy of the floating types. It provides no types or functions
What does the limits.h header provide? What doesn’t it provide?
Macros that define the range of each integer and character type. It provides no types or functions.
What is does the ctype.h header contain?
2 kinds of functions:
character testing functions
character case-mapping functions
What is the stdarg.h header used for?
Writing functions of variable length argument lists.
What are the 4 components needed to create a function with a variable length argument list?
va_list - needed to iterate through the arguments
va_start - needed to indicate where the arg list starts
va_arg - fetches the arguments and advances the pointer
va_end - required to clean up before the function can return
What is linkage?
The extend to which a variable can be shared by different parts of a program
What are the different types of linkage?
external - shared by several files
internal - shared by functions in a file
no linkage - belongs to a single function