The Pragmatic Addict

Useful C define functions

Over the past 20 years I’ve writing quite a bit of cross platform C code using gcc and mingw. These are some quick functions I’ve reached for which save a bunch of mundane coding.

The key advantage to use macro definitions rather than functions is performance speed. If these were a function, all the overhead (poiters, stacks etc) would be needed each time the function were called. In this way the code is executed directly saving clock cycles and resources.

Chomp

In my early days of coding I wrote a lot of Perl. One of the functions I used a bunch was ‘chomp’. This function chops off the CR & LF characters off the end of a string. This is most commonly called after reading a string from a file (fgets). This does require string.h for use.

#include <string.h>
#define CHOMP(s) s[strcspn(s,"\r\n")]='\0';

Bitwise Operations

This functions were used quite a bit in my work with the dymo label maker. Bit position is indexed 0-7.

#define CLEAR_BIT(value,pos) (value &= (~(1U<<pos)))
#define FLIP_BIT(value,pos) (value ^= (1U<<pos))
#define GET_BIT(value,pos) ((value>>pos)&1)
#define SET_BIT(value,pos) (value |= (1U<<pos))

Created: 2024-04-11 Modified: 2024-04-13