• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

C++ Preprocessor Snippets

Contents

  • Maximum / Minimum
  • Absolute Value
  • Swap variable content
  • See also

The C++ Preprocessor - which is in fact the same as the C Preprocessor - provides some very basic, but powerful abilities. I haven't used them quite often, but I have seen some nice examples. So here are some C++ Preprocessor Snippets:

Maximum / Minimum

If you want to find the maximum / minimum of two elements, no matter of which type, you can do something like this:

#include <iostream>

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

using namespace std;

int main() {
    cout << MAX(42, 1337) << endl;
    cout << MAX(1337, 42) << endl;
    cout << MAX(-1337, 42) << endl;
    cout << MAX(1337.0, 42) << endl;
    return 0;
}

Absolute Value

You can get the absolute value like this:

#include <iostream>

#define ABS(a) (a < 0 ? -(a) : a)

using namespace std;

int main() {
    int a = 42, b = -43, c = 0, d = -1337;

    cout << ABS(a) << endl;
    cout << ABS(b) << endl;
    cout << ABS(c) << endl;
    cout << ABS(d) << endl;
    return 0;
}

By the way, brackets around a are important, because without them you could get:

a=1,b=3
ABS(a-b) = ABS(1-3) = (1-3 < 0 ? -1-3 : 1-3) = -2 < 0 ? -4 : -2 = -4

Swap variable content

This is an example for a multiline replacement.

#include <iostream>

#define SWAP(a, b)  {   int tmp; \
                        tmp = b; \
                        b = a;   \
                        a = tmp; \
                    }

using namespace std;

int main() {
    int a = 42, b = 1337;
    swap(a, b);
    cout << a << endl;
    cout << b << endl;
    return 0;
}

See also

  • Wikipedia: C preprocessor
  • Tips and tricks using the preprocessor: Part one - part two
    A very good article about the meaning of #import, #error, #pragma. It is written very well and has some examples.
  • Obfuscated C: Calculate PI

Do you know more preprocessor snippets that are used very often or which are interesting?

Published

Dez 25, 2012
by Martin Thoma

Category

Code

Tags

  • C 23
  • Preprocessor 1

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor