Notes from The C Book.
- To use
exit()
,EXIT_SUCCESS
andEXIT_FAILURE
includestdlib.h
.
- Include
<stddef.h>
to usewchar_t
-
Qualified types --
const
andvolatile
.int i; // ordinary int
const int ci = 1 ; // constant integer
const int *pci ; // pointer to a constant int
int *const cpi = &i; // constant pointer to an int
const int *const cpci = &ci; //constant pointer to a constant int
-
sizeof
is implementation dependent. It will be eitherunsigned long
orunsigned int
.- Use
size_t
provided in the<stdlib.h>
--size_t sz; sz = sizeof(sz);
- Cast the return value to
unsigned long
. --(unsigned long)sz;
.
- Use
-
Use
stdlib.h
to declare malloc correctly. -
Fundamental unit of storage in C is
char
. -
malloc
returns a null pointer if it cannot allocate requested free space. -
stdio.h
contains defined constantNULL
. alternatively, use0
or(void *)0
. -
Pointers to functions --
int (*func)(int a, int b);
-
call the function with --
(*func)(1,2);
orfunc(1,2);
. -
An incomplete type is one whose name and type are mostly known, but whose size isn't yet been determined.
-
A function is not an object.
-
To get an incomplete type:
- declare an array omitting info about it's size --
int x[];
- declare a
struct
orunion
but not defining it's contents.
- declare an array omitting info about it's size --
-
Pointers void can be converted backwards and forwards with ptrs to any object or incomplete type.
-
An unqualified ptr may be converted to a qualified ptr. The reverse is not true.
-
struct wp_char wp_char;
-- This defines a var calledwp_char
of typewp_char
. This means tags have their own namespace and cannot collide with other names.struct wp_char{ char wp_cval; short wp_font; short wp_psize; }
struct wp_char v2;
-
Pointer to the structure --
struct wp_char *wp_p;
-
Access --
(*wp_p).wp_cval;
(.
has higher precedence than *, hence the parens). -
Or
wp_p->wp_cval
.
#include #include struct somestruct{ int i; }; main(){ struct somestruct *ssp, s_item; const struct somestruct *cssp; s_item.i = 1; /* fine */ ssp = &s_item; ssp->i += 2; /* fine */ cssp = &s_item; cssp->i = 0; /* not permitted - cssp points to const objects */ exit(EXIT_SUCCESS); }
In the above code, cssp->i = 0;
tries to assign value to a const object; gcc
does not allow this behaviour. tcc
does.
- Storage Layout -- Addressing restrictions might create "holes" in the structures. Eg:
char|(hole)|short|short
because char occupies one byte and shorts are expected to start from even numbered addresses.