restrict: the only C keyword with no C++ equivalent

restrict: the only C keyword with no C++ equivalent

The restrict keyword in C is the only keyword that has no analogue in C++. The keyword promises to the compiler that objects accessible through the pointer will not be accessed (either read or written to) through any other means than through the restrict pointer. This promise to the compiler allows more potential optimizations, including removing redundant reads and potentially allowing automatic vectorization, which can lead to smaller and faster code. However, if you use it incorrectly, restrict can be the source of some seriously hard to find bugs because they may only appear at high optimization levels and not in your testing or debugging builds. Major C++ compilers do support restrict in a non-standardized way though, so if you are willing to write code that is specific to your compiler, then you may still be able to take advantage of restrict even though it is not part of standard C++.

Erratum: In the fib_upto_n example the check for n==0 should go before the write to dst[0], and the check for n==1 should go before the write to dst[1], it is fixed in the GitHub link. I'm very confused why I ever wrote it that way, but that's what I get for not writing tests :). This did not affect anything in the video because I was using n=10.

― mCoding with James Murphy (https://mcoding.io)

Source code: https://github.com/mCodingLLC/VideosSampleCode
Compiler explorer: https://godbolt.org/z/4EzvTGcfo
restrict keyword: https://en.cppreference.com/w/c/language/restrict
StackOverflow on restrict: https://stackoverflow.com/questions/745870/realistic-usage-of-the-c99-restrict-keyword

SUPPORT ME ⭐
---------------------------------------------------
Sign up on Patreon to get your donor role and early access to videos!
https://patreon.com/mCoding

Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)
https://www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJHEE

Top patrons and donors:
Laura M, Jameson, John M, Pieter G, Vahnekie, Sigmanificient

BE ACTIVE IN MY COMMUNITY πŸ˜„
---------------------------------------------------
Discord: https://discord.gg/Ye9yJtZQuN
Github: https://github.com/mCodingLLC/
Reddit: https://www.reddit.com/r/mCoding/
Facebook: https://www.facebook.com/james.mcoding

CHAPTERS
---------------------------------------------------
0:00 Intro
0:58 Restrict explanation
3:42 Vector add example
6:28 Correctness fib example
9:06 Best practices, memcpy and memmove
10:21 Restrict in C++
12:41 Thanks

C++C programmingrestrict keyword

Post a Comment

0 Comments