C Knowledge Flashcards
Standard ‘MIN’ Macro
define MIN(A,B) ((A) <= (B) ? (A) : (B))
Conditional expression with ternary operator
expr1 ? expr2 : expr3
expr1 is evaluated first
If true (non-Zero), then expr2 is evaluated.
Otherwise, expr3 is evaluated.
Code an infinite loop
while(1)
for(;;) //KnR preferred method, necessary for Lint
Loop:
goto Loop;
What are the three uses of the keyword static?
a. A variable declared static within the body of a function maintains its value between function calls
b. A variable declared static within a module, but outside a function, is accessible by all functions within that module. (localized global)
c. Functions declared static w/in a module may only be called by other functions within that module. The scope of the function is localized to the module in which it was declared.
What does the keyword const mean?
essentially “ready-only”
const int a;
or
int const a;
read-only integer
const int *a;
pointer to a read-only integer. (integer isn’t modifiable, but pointer is)
int * const a;
read-only pointer to a modifiable integer
int const * a const;
constant pointer to a constant integer
What does the keyword volatile mean?
( volatile == a qualifier) A volatile variable is one that can change unexpectedly. Tells optimizer that the variable must reload the variable every time it is used instead of holding a copy in a register.
Give three examples of using the volatile keyword.
- Hardware registers in peripherals (e.g., status registers)
- Non-stack variables referenced within an interrupt service routine.
- Variables shared by multiple tasks in a multi-threaded application
Can a parameter be both const and volatile?
Yes. Example: read-only status register. Volatile because it can change unexpectedly, const because the program should not attempt to modify it.
Can a pointer be volatile?
Yes. Example: when an interrupt service routine modifies a pointer to a buffer
What is wrong with following function:
int square(volatile int *ptr)
{
return *ptr * *ptr;
}
Since *ptr is volatile and could change unexpectedly, it could produce a return value that is not a square. Function should set a local variable with the value of *ptr and then square the local variable.
Efficient way to produce Bit manipulation?
define SET_BIT(x,y) (x |= (1«y))
Set Bit |=
Clr Bit &= ~
#define CLR_BIT(x,y) (x &= ~(1«y))