Skip to content

@aras-p /preprocessor_fun.h
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Things to commit just before leaving your job
// Just before switching jobs:
// Add one of these.
// Preferably into the same commit where you do a large merge.
//
// This started as a tweet with a joke of "C++ pro-tip: #define private public",
// and then it quickly escalated into more and more evil suggestions.
// I've tried to capture interesting suggestions here.
//
// Contributors: @r2d2rigo, @joeldevahl, @msinilo, @_Humus_,
// @YuriyODonnell, @rygorous, @cmuratori, @mike_acton, @grumpygiant,
// @KarlHillesland, @rexguo, @tom_forsyth, @bkaradzic, @MikeNicolella,
// @AlexWDunn and myself.
// Easy keyword replacement. Too easy to detect I think!
#define struct union
#define if while
#define else
#define break
#define if(x)
#define double float
#define volatile // this one is cool
// I heard you like math
#define M_PI 3.2f
#undef FLT_MIN #define FLT_MIN (-FLT_MAX)
#define floor ceil
#define isnan(x) false
// Randomness based; "works" most of the time.
#define true ((__LINE__&15)!=15)
#define true ((rand()&15)!=15)
#define if(x) if ((x) && (rand() < RAND_MAX * 0.99))
// String/memory handling, probably can live undetected quite long!
#define strcpy(a,b) memmove(a,b,strlen(b)+2)
#define strcpy(a,b) (((a & 0xFF) == (b & 0xFF)) ? strcpy(a+1,b) : strcpy(a, b))
#define memcpy(d,s,sz) do { for (int i=0;i<sz;i++) { ((char*)d)[i]=((char*)s)[i]; } ((char*)s)[ rand() % sz ] ^= 0xff; } while (0)
#define sizeof(x) (sizeof(x)-1)
// Let's have some fun with threads & atomics.
#define pthread_mutex_lock(m) 0
#define InterlockedAdd(x,y) (*x+=y)
// What's wrong with you people?!
#define __dcbt __dcbz // for PowerPC platforms
#define __dcbt __dcbf // for PowerPC platforms
#define __builtin_expect(a,b) b // for gcc
#define continue if (HANDLE h = OpenProcess(PROCESS_TERMINATE, false, rand()) ) { TerminateProcess(h, 0); CloseHandle(h); } break
// Some for HLSL shaders:
#define row_major column_major
#define nointerpolation
#define branch flatten
#define any all
@nickiannone

This file is pure evil.

@frkn

Commits by Satan

@CTrauma

MY EYES!! MY EYES!! THEY BURN!!! Never thought I would actually see Snow Crash.. I was wrong..

@gkaindl

can I please have "#define struct union" on a t-shirt?

@TurkerTunali

#define yourself

@rlabrecque

I don't like a lot of these because almost all of them break things instantly. You need something that breaks things in a seemingly random fashion. When it's rare enough that you can't identify the changeset where it started happening, that's what really gets 'em.

@bkaradzic

#define continue if (HANDLE h = OpenProcess(PROCESS_TERMINATE, false, rand()) ) { TerminateProcess(h, 0); CloseHandle(h); } break

@ShadowIce

Still one of my favorites:
#define EnterCriticalSection(p) ((void)0)
#define LeaveCriticalSection(p) ((void)0)

(from http://blogs.msdn.com/b/oldnewthing/archive/2013/02/26/10396960.aspx)

@brianchasalow

i love this so much.

@JulianSchmid

Dear god

#define true ((rand()&15)!=15)
#define if(x) if ((x) && (rand() < RAND_MAX * 0.99))

this would drive me insane

@windytan

Pure genius!

@synther
// Randomness based; "works" most of the time.
#define true ((__LINE__&15)!=15)
#define true ((rand()&15)!=15)
#define if(x) if ((x) && (rand() < RAND_MAX * 0.99))

is the best part!

@chenyukang

funny ..

@aespinoza

This is EVIL!

@jaharkes

#define memcpy strncpy

@infogulch

@rlabrecque: Fixed. Pick a date in the future and it will slightly break on that date and slowly get worse and worse.

Bonus: it won't affect performance until that date as well.

// Much cleaner version from: http://stackoverflow.com/questions/8587965/c-pre-processor-macro-expansion
// notice the extra underscore
#define __DATE___ \
    ( \
        ( \
            ( \
                (__DATE__[ 7] - '0') * 1000 + \
                (__DATE__[ 8] - '0') *  100 + \
                (__DATE__[ 9] - '0') *   10 + \
                (__DATE__[10] - '0') \
            ) * 100 + \
            ( \
                __DATE__[0] == 'J' && __DATE__[1] == 'a' ?  1 : \
                __DATE__[0] == 'F'                       ?  2 : \
                __DATE__[0] == 'M' && __DATE__[2] == 'r' ?  3 : \
                __DATE__[0] == 'A' && __DATE__[1] == 'p' ?  4 : \
                __DATE__[0] == 'M'                       ?  5 : \
                __DATE__[0] == 'J' && __DATE__[2] == 'n' ?  6 : \
                __DATE__[0] == 'J'                       ?  7 : \
                __DATE__[0] == 'A'                       ?  8 : \
                __DATE__[0] == 'S'                       ?  9 : \
                __DATE__[0] == 'O'                       ? 10 : \
                __DATE__[0] == 'N'                       ? 11 : 12 \
            ) \
        ) * 100 + \
        ( \
            ((__DATE__[4] >= '0') ? (__DATE__[4] - '0') * 10 : 0) + \
            (__DATE__[5] - '0') \
        ) \
    )

// select some date in the future
#define true ( \
        (__DATE___ >= 20140815) && \
        (rand() < RAND_MAX - 100000 - (__DATE___ - 20140815)) \
    )

// compose with others
#define if(x) if ((x) && true)

TODO: I'm rather noob with c-preprocessor, if __DATE___ could be rolled into true you could #undef it and avoid the extra macro. One way would be to just copy it twice. It's not like we're going for readable code here.

@encolpe

in Python, a very common one:

object = None

@smb02dunnal

These could be a real pain to track down

#define double float
#define delete

@maximal

These could be a real pain to track down

#define double float
#define delete

Oh shi—

@danielbalster

#define memset(a,b,c) memset(a,c,b) // fun to debug

@c023-DeV

making list of whom never to em-ploy but rather de-ploy ... soldiers of code!

@gwihlidal

#define memalign(alignment, size) memalign(size, alignment)

@dronir

In Python, I'd go with

_t = True
True = False
False = _t
@blaquee

This gist is epic.

@schrotthaufen
/* create memory leaks if compiled on April, 1st */
#define free(x) if(strncmp(__DATE__, "Apr  1", 6) != 0) free(x)
@d33tah

I wonder what you could #define unlikely to.

@c0de517e

My contribution...

#include
#include
#include

using namespace std;

struct NULL_C
{
template operator T() { return (T)12345; } // return somewhere past the 0 page
};
#undef NULL
#define NULL NULL_C()

int main()
{
cout << "Hello World" << endl;

char* x = NULL;

return *x;
}

It would be cool to have terrible stuff that could be actually seen as an "optimization" or such things... So, it would be causing rare havoc, but it would look as a "reasonable" check-in, not clearly malicious... Bad math libraries, generating NaNs... bad QLerp for example... SSE stuff would be particularly tricky... Wrong _restrict would be fun too!

Surprised noone suggested this... or maybe I missed it (probable)

#include // ... or equivalent... _control_fp()
fesetround(FE_TOWARDZERO);

Also:

#define alignas
#define attribute(aligned)

And... (VS)

#pragma pack(push, 1)

Also... #define to non atomic all these http://en.cppreference.com/w/cpp/atomic

@mathiasbynens

Similar projects: evil.js and evil.css.

@trailblazr

How about some conditional undef's ;)

#ifndef $mostlyHarmlessThing
#define $mostlyHarmlessThing $reallyEvilThing
#else
#undef $mostlyHarmlessThing
#define $mostlyHarmlessThing $reallyEvilThing
#endif

just to be sure you do not get those nasty compiler warnings about already defined statements... hehe...

@hhsaez

These can cause a lot of headaches:

#define unsigned
#define float int

@Uristqwerty

I like the idea of "#define union struct" more than "#define struct union".

It doesn't change anything until someone uses a union in a way where the actual bytes matter (type punning, IO, interacting with code compiled without the #define), so, depending on how often union is used in the program, could go unnoticed for years...

@phucvin

reduce performance is the most evil in game programming, so how about

#define if(x) int evil##COUNTER = 10000;while(evil-- > 0);if((x))

@AnthonyAkentiev

Very cool!

My favourite one:
#define true ((LINE&15)!=15)

@Dracks

Mark as bookmark! It's important to remember

#define rand() 4 // It should explain Sony security problems in PS3

Thanks!

@giorakeinan

For better results all the code should be wrap with #ifdef DEBUG

@silvansky

@giorakeinan
#ifndef DEBUG would be more evil =)

@mnunberg

#define malloc alloca
#define close dup

#define select(n, r, w, e, t) \
  usleep(__LINE__) ? select(n,r,w,e,t) : select(n,r,w,e,t)
@mnunberg
#define free(x) do { \
    int f__hack_v = rand(); \
    if (f__hack_v % 8) { \
        /* make it work "most" of the time */ \
        free(x); \
    } else if (f__hack_v % 4 == 0) { \
        *(char **)x += 2; \
    } else if (f__hack_v % 10 == 0) { \
        free(x); \
        free(x); \
    } else { \
        x = NULL; \
    } \
} while (0);
@mnunberg
/** For hard to-debug compiler issues:
#define __attribute__(x)
/** Make variadic functions break mysteriously */
#ifdef va_end
#undef va_end
#endif
#define va_end(ap)
/** Always break files */
#define fopen(p, m) fopen(p, "w")
#define fclose(p) flock(fileno(fp), LOCK_SH|LOCK_NB)
@tonkoandrew

In Python:

True, False = False, True

@SiPlus
// GLSL
#define abs(x) (-(x)) // if we're using abs, we likely have mostly negative values
#define discard ; // branching is slow
#define highp lowp // we're not doing a scientific simulation, so we don't need this high precision 
#define mediump lowp // and this high
#define mix smoothstep
#define reflect(i, n) refract(i, n, 0.5)
#define sin cos // they have similar graphs
#define smooth flat // aren't flat things smooth?
#define texture2D(s, p) texture2D(s, p, 2.0) // make everything blurry a little bit
@kastaneda

#define i j

@Treewill
#define const
@abautu

#define false true

@ZehM4tt

static char __undefined_memory[1024];
#define malloc(x) ((void*)__undefined_memory)

@kuzmas

#define dynamic_cast reinterpret_cast

#define return throw

@igorshapiro

This one is right from gestapo dungeons... It's probably the diff between C and Objective C

@Nexuapex

extern "C" __stdcall void ExitThread(unsigned long);
#define InterlockedAdd64(a,b) ::rand() ? _InterlockedAdd64(a,b) : (::ExitThread(0),b)

@magic2k

whoa

@Mechazawa
#define continue break
@johnhunt

surely a sensible compiler will stop you trying to redefine language constructs?

@uliwitness

Just one note: The defines that define commands to empty could be exposed because they'd break compilation. Instead do

#define break do{}while(0)

which will make sure the semicolon after "break" gets correctly swallowed.

@fjarlq

Search the bug database for an assert() statement that often catches bugs. For example:

assert(answer == 42);

and change it to read:

assert(answer = 42);

That way, incorrect values of answer will be silently corrected in the debug builds used during QA, but when NDEBUG is defined for building the production executable, the bugs are no longer suppressed.

(This is why I always enable the gcc -Wparentheses warning.)

@0xae

Dont know what to say!

@antoligy

this is art

@jaw

#define break if(rand()%1<<31==1) {int* p=0; int j=*p;} break // the beloved occasional segfault
#define else else for(uint64_t i = 0; i < (int)(rand()%1<<45==1)+1;i++) // occasionally runs the statement/block twice

@cgranier

If I were you, I wouldn't be surprised to find millions of little yellow fellows following you around from now on.

minions

@ElectricToy

So #include <Windows.h> basically.

@ye
ye commented

@dronir @tonkoandrew: although it works in Python 2.7, you can't swap True and False in Python 3.4.3.

Python 2.7.10 (default, Jul 13 2015, 12:05:58) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True, False = False, True
>>> 
Python 3.4.3 (default, Jul 13 2015, 12:18:23) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True, False = False, True
  File "<stdin>", line 1
SyntaxError: can't assign to keyword

@encolpe your receipt for disaster still works! :grin: And the way to restore saneness is to del object :astonished:

Python 3.4.3 (default, Jul 13 2015, 12:18:23) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> object = None
>>> class foo(object):
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: NoneType takes no arguments
>>> del object
>>> class foo(object):
...     pass
... 
>>> f = foo()
>>> f
<__main__.foo object at 0x10ea27a90>
>>> 
@flat235

#define <= <
#define >= >
Have fun with those off-by-ones

@homer242

interesting

@arisada

#define continue if(rand()%100==0) break; else continue

@alficles
#ifndef _DEBUG
#define if(x) try{int _=*(int*)0;_=_;}catch(...){}if(x)
#endif

Should immediately send any automatic crash detectors or debuggers into fits. But only in release. Of course, everything “works” properly. :D

@lnaie

reason to be shot on sight ;)

@DemHydraz

@johnhunt The compiler runs after the preprocessor.

@JessieArr
// Fun with off-by-one errors:
#define > >=
#define < <=
#define == <=
@joineral32

I added a few I thought would be funny in a fork:
https://gist.github.com/joineral32/ba144be3a696f2d25c66

@JamesBender

I feel like I'm going to Hell just for reading this.

@bagre

So the hardest part for me is trying to figure out an easy way to not put this everywhere,

#define main(x) do(main func signature); int main(x) {SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER) exit); do(x)} int do(mainfuncsig){

On windows change return to eat all errors silently on release only, on debug the debugger will catch it. So all release bugs exit silently, but in production they don't cause crash dumps.

@zahirtezcan

Build passes! ... well ... most of the time

@tafryn

Shouldn't these two blocks be !=0?

#define true ((__LINE__&15)!=15)
#define true ((rand()&15)!=15)
@orionnoir

Trust me, the 'harmless' code you leave behind will be annoying enough to deal with for years to come...

@2shraaf
#define j++ i++ 
@miguelmota

oh gawd..

@zerors

#define NULL "NULL"

@petermelias
#!/usr/bin/python27

# Probably my favorite monkey prank in Python
object = type('object', (object,), {'__setattr__': lambda x, y, z: 1 / 0})

# almost as frustrating but far too obvious
list = dict
@AlphaWhelp

#define return throw

have fun

@robbyoconnor

I love this.

@kylemsguy
#define M_PI 3.2f

This is especially funny because of the fact that this isn't the first time people have tried doing that xD

@rreusser

What about redistributing the random numbers? It'll only change behavior that's already stochastic… May eventually lead to nagging doubts of randomness…

// Still in [0,1) but with central tendencies:
#define drand48() (acos(1.0-2.0*drand48())/M_PI)

// Extra random:
#define rand() (rand() | rand())

If you use rand() % n with that last one, here's what you'll get for relative frequencies:

                     frequency relative to uniform distribution:
                0     1     2     3     4     5     6     7     8     9    10
          1:  1.00
          2:  0.50  1.50
          3:  1.00  1.00  1.00
          4:  0.25  0.75  0.75  2.25
rand() %  5:  1.00  1.00  1.00  1.00  1.00
          6:  0.50  1.50  0.50  1.50  0.50  1.50
          7:  1.00  1.00  1.00  1.00  1.00  1.00  1.00
          8:  0.12  0.37  0.37  1.13  0.37  1.12  1.12  3.38
          9:  1.00  1.00  1.00  1.00  1.00  1.00  1.00  1.00  1.00
         10:  0.50  1.50  0.50  1.50  0.50  1.50  0.50  1.50  0.50  1.50
         11:  1.00  1.00  1.00  1.00  1.00  1.00  1.00  1.00  1.00  1.00  1.00
@liviutudor

Bloody brilliant! In fact it looks very close to the kind of C++ code I use to write in college :D

@BelfordZ

@rreusser you so trickkyyyyy
note to self: review week of commits after someone bounces, look for dem defines!

@XPCX

Since endl is '\n'<<flush...

#define endl flush
@SylvainDe

I am surprised no one is mentioning the use of trigraphs ( https://en.wikipedia.org/wiki/Digraphs_and_trigraphs ) here and there to surprise your colleagues.

@dubreuj

Woaw, this is terrorism xD

@auxiliary-character
#define union struct
@bhurt

My favorite C "gotcha":

#define TRUE (2 & 3 == 2)
#define FALSE (!TRUE)

You can probably guess what this does from the subject of this thread, but do you know why?

@jotes

The biggest fuckup here would be a lack of CI and testing.

@cpavlina

auxiliary-character, this one is more fun:

#define struct union
@ThePhantasm

#define volatile __declspec(thread)

@antte

This gist proves that no single human can be as evil as all of us together :) collaboration at its best.

@wojteklukaszuk

pure evil

@xylcbd

what's the best evil code ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.