Skip to content

Instantly share code, notes, and snippets.

View shafik's full-sized avatar

Shafik Yaghmour shafik

View GitHub Profile
@shafik
shafik / lex_pptoken_undefined_behavior_and_preprocessor.md
Last active December 20, 2023 10:03
Interesting undefined behavior in lex.pptoken/p2

The following code has an interesting form of undefined behavior:

#define STR_START "
#define STR_END "

int puts(const char *);

int main() {
 puts(STR_START hello world STR_END);
@shafik
shafik / ThisIsJustToSayC++CompilerEditiion.md
Last active June 2, 2021 02:19
This is Just to Say for C++ Compilers

This Is Just to Say

I have translated
the program
that was in
the translation units

and which
you were probably
expecting

@shafik
shafik / WhatIsStrictAliasingAndWhyDoWeCare.md
Last active April 8, 2024 04:31
What is Strict Aliasing and Why do we Care?

What is the Strict Aliasing Rule and Why do we care?

(OR Type Punning, Undefined Behavior and Alignment, Oh My!)

What is strict aliasing? First we will describe what is aliasing and then we can learn what being strict about it means.

In C and C++ aliasing has to do with what expression types we are allowed to access stored values through. In both C and C++ the standard specifies which expression types are allowed to alias which types. The compiler and optimizer are allowed to assume we follow the aliasing rules strictly, hence the term strict aliasing rule. If we attempt to access a value using a type not allowed it is classified as undefined behavior(UB). Once we have undefined behavior all bets are off, the results of our program are no longer reliable.

Unfortunately with strict aliasing violations, we will often obtain the results we expect, leaving the possibility the a future version of a compiler with a new optimization will break code we th

@shafik
shafik / bit_cast_array.md
Last active June 29, 2021 14:45
How to use bit_cast to type pun a unsigned char array

In C++20 we will hopefully get bit_cast see the proposal and reference implementation. This utility should give us a simple and safe way to type pun.

The one issue I ran into with this utility is that is requires the size of the To and From type to be the same, as well as checking that To and From types are trivially copyable. The static_assert version of the check is as follows:

# define BIT_CAST_STATIC_ASSERTS(TO, FROM) do {                         \
    static_assert(sizeof(TO) == sizeof(FROM));                          \             
    static_assert(std::is_trivially_copyable<TO>::value);               \
    static_assert(std::is_trivially_copyable<FROM>::value);             \
} while (false)