C_quicknotes

Takeaways from the book “Advanced C Programming” by Berry, John Thomas.

While it’s titled “advanced”, it is rather basic. Here is some quick notes on stuff that I’m not familar with/ don’t use often.

define variables as global to a small region of program

Global variables always involves the possibility of side effects. By keeping the coupling well controlled, we minimize some of this danger.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// stack and top are global to push() and pop(), but hidden from main().
void push();
void pop();
int main(){
// calling push() and pop()
}

int top;
void* stack[100];

void push(){
// .. pushing to the stack
}

void* pop(){
// .. popping from the stack
}

Using stack to hide global variables from the rest of the program

main.c

1
2
3
4
5
6
7
8
9
// stack and top can still be accessed here
// by declaring them with extern.
// or worse, main.c can declare them as global again
// causing problems...

extern void* stack[];
extern int top;
int main(){
}

lib.c

1
2
3
4
int top;
void* stack[100];
void push(){...};
void pop(){...};

to avoid this, declare the global variables as static so that their scopes are restricted only to the home file.

1
2
static double stack[100];
static int top=0;

Declaring functions in main to limit the scope: only use there!

1
2
3
4
5
6
7
8
9
int main(
int foo();
foo();

)

int foo(){
// ...
}

Bitfield

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
typedef struct _bf{
    int f1:1,
        f2:1,
        f3:1;
}flags;

int main(){
    flags bf;
    bf.f1 = 0;
    bf.f2 = 1;
    bf.f3 = 1;

    // check flag
    if(bf.f1) // do ..
    
}
edited 13.01.2023
created 08.08.2022
EOF
[+] click to leave a comment [+]
the comment system on this blog works via email. The button
below will generate a mailto: link based on this page's url 
and invoke your email client - please edit the comment there!

[optional] even better, encrypt the email with my public key

- don't modify the subject field
- specify a nickname, otherwise your comment will be shown as   
  anonymous
- your email address will not be disclosed
- you agree that the comment is to be made public.
- to take down a comment, send the request via email.

>> SEND COMMENT <<