Skip to content

Programming Tricks, Part 1

angrave edited this page Oct 24, 2014 · 10 revisions

Use cat as your IDE

Who needs an editor? IDE? We can just use cat You've seen cat being used to read the contents of files but it can also be used to simple echo back the output from standard-input stream

>cat
HELLO
HELLO

Let's use cat to send standard input to a file. We will use '>' to redirect output to a file:

>cat > myprog.c
#include <stdio.h>
int main() {printf("Hi!");return 0;}

(Be careful! Deletes and undos are not allowed...) To tell the cat process the file has finished we need to close the input stream by pressing CTRL-D

Edit your code with perl regular expressions (aka remember pie)

A useful trick if you have several files to change is to use regular expressions. perl makes this very easy to edit files in place. Just remember 'perl pie' and search on the web...

An example. Suppose we want to change the sequence "Hi" to "Bye" in all .c files in the current directory...

perl -p -i -e 's/Hi/Bye/' *.c

(Don't panic, original files are still there; they just have the extension .bak) Obviously there's a lot more you can do with regular expressions than changing Hi to Bye.

gcc &&

Tired of running make or gcc and then running the program if it compiled OK? Instead, use && to chain these commands together

gcc program.c && ./a.out

Is your neighbor too productive? C pre-procesors to the rescue!

Use the C pre-processor to redefine common keywords e.g.

#define if while

Protip: Put this line inside one of the standard includes e.g. /usr/include/stdio.h

Who needs functions when you C have the preprocessor

OK, so this is more of a gotcha. Be careful when using macros that look like functions...

#define min(a,b) a<b?a:b

A perfectly reasonable definition of a minimum of a and b. However the pre-processor is just a simple text wrangler so precedence can bite you:

int value = -min(2,3); // Should be -2?

Is expanded to

int value = -2<3 ? 2 :3; // Ooops.. result will be 2

The fix is to wrap every argument with ()and also the whole expression with ():

#define min(a,b) (  (a) < (b) ?(a):(b) )

However this is still not a function. For example can you see why min(i++,10) might implement i once or twice!?

Clone this wiki locally