We want our code, in C or C++ in this case, to be as robust as possible. By “Robust” I mean resilient to bugs, changes and surprises. We can increase our code’s run-time robustness by employing various good coding practices, “assert” constructs or even just ‘if’ statements in the right places to protect against broken assumptions and other dire straights. But wouldn’t it be so much better if we can catch problems before even running a single line of code? The C_ASSERT macro will do just that.
C_ASSERT
The C_ASSERT macro is what you need in order to protect your code against many problems, at compilation time. It can defined like suggested here in the Microsoft knowledge base, or like the following which is better in my view since it avoids many caveats of unique usage and more:
#define C_ASSERT(phrase) extern char _C_ASSERT_[(phrase) ? 1 : -1]
This declares the existence of an external array, based on the evaluation of the given phrase. If the phrase evaluates as true, it will declare the external array _C_ASSERT_ to be a char array of size 1. Otherwise, it will declare it as a char array of the illegal size -1. This will fail the compilation.
Why define C_ASSERT like that?
This is definition makes sense since:
- There is no “cost” here, no memory-consuming entity is being defined, just a non-binding declaration. You don’t really need to have such an array anywhere
- The macro can be used in multiple locations without collisions
- The macro can be used inside and outside of scopes
You can see a detailed discussion on how this macro can be defined in this great pixelbeat post, to which I give credit for the idea of using ‘extern’.
Build Time Robustness
With this little tool at hand, we can do a much better job at maintaining Build Time Robustness. We can use C_ASSERT to “bind” some of our defined constructs to each other’s limitations, to assert assumptions that must not break, or just express changeable assumptions with code instead of comments. Following are several examples.
Bit Field guarding
Let’s assume you have defined a small Bit Field (see more about Bit Fields in my post about Masks VS. bitfields), and you plan that field to express values that are defined by an enum. Your code may look like this:
typedef struct
{
unsigned int color : 3;
unsigned int shape : 1;
unsigned int RSVD : 28;
}OBJECT;
typedef enum
{
COLOR_BLUE = 0,
COLOR_RED = 1,
COLOR_YELLOW = 2,
COLOR_MAX // Leave that last!!
}COLORS;
typedef enum
{
SHAPE_ROUND = 0,
SHAPE_RECT = 1,
SHAPE_MAX // Leave that last!!
}SHAPES;
When you try to assign a large number to a small field directly (with immediate value), the compiler will stop you, which is good. However this is a “thin” protection mechanism. For example, you can assign a function argument that can contain large numbers into a small field, and it will pass compilation:
OBJECT * allocate_object(COLORS color, SHAPES shape)
{
OBJECT * object = (OBJECT*)malloc(sizeof(OBJECT));
// ‘color’ might contain a large number
object->color = color;
// ‘shape’ might contain a large number
object->shape = shape;
return object;
}
If the COLOR or SHAPE enums are ever enlarged, it can break this code that has a hidden dependency in it: the enums are defined with maximum values that are supposed to fit into the respective bit fields.
We can mitigate the problem by adding a C_ASSERT at the right place. Where is that? I personally put it in the using location, not at the definition of the problematic entity. So in this case, I would not put it at the definition of the enums, but at the definition of the OBJECT struct, in the function at danger, or in both. No need to use C_ASSERT sparingly,it is free! It has an effect only during the build, not during runtime.
typedef struct
{
unsigned int color : 3;
unsigned int shape : 1;
unsigned int RSVD : 28;
}OBJECT;
C_ASSERT(COLOR_MAX <= 8);
C_ASSERT(SHAPE_MAX <= 2);
OBJECT * allocate_object(COLORS color, SHAPES shape)
{
OBJECT * object = (OBJECT*)malloc(sizeof(OBJECT));
C_ASSERT(COLOR_MAX <= 8);
object->color = color;
C_ASSERT(SHAPE_MAX <= 2);
object->shape = shape;
return object;
}
If I try to add the element SHAPE_TRIANGLE to SHAPES and compile, I get this:
Bingo!
Struct size fortification
Another example: Assume you have a struct comprised of other structs. For reasons of binary backwards compatibility, your struct must stay at a fixed size (say 3 DWORDS == 12 bytes). If anyone (you?) goes and changes one of the underlying struct definitions, it can break that restriction without anybody noticing. We want it to at least be noticed so the problem can be addressed. Here is how you can define such a struct, while using C_ASSERT to guard against un-noticed size changes:
typedef struct
{
HEADER header;
FLAGS flags;
DATA data;
}PACKET;
C_ASSERT(sizeof(PACKET) == 12);
This “locks” the struct to exactly that size. It can be changed if needed, but it will save you from bad surprises.
Summary
This little macro can save you lots of tears, and the two examples above come from stories I had in real life. I will use that macro extensively in future posts about Build-Time robustness, stay tuned!
156 Comments
beastiality dating canada singles chat free dating sites no fees sites online dating
essay writing assignment help custom essay service
essay service cheap are essay writing services legal
what is the best online essay writing service reliable essay writing service who can i pay
to write my essay best essay cheap
law school essay review service essay on service higher english
essay help cheapest essay writers
cheapest custom essay writing professional college application essay writers
custom admission essay custom essay cheap
help with argumentative essay write my essay for money
essaywriting service custom order essays
easy essay help custom writing essay common app essay help custom essays services
english essay writers help with essays cambridge essay service essay writing service law school
write my essay students essay writing services review help with writing essays at university discount essay writing service
custome essay write my essay generator homework essay help help with writing essay
best college essay writing service custom writing essay essay proofreading services top custom essay services
best vpn for binance what is the best free vpn setup vpn best torrent vpn
ipvanish vpn free free vpn for chromebook buy vpn servers cyberghost vpn free trial
online free vpn vpn for mac free hide vpn best vpn for torrenting
best free vpn app for windows free vpn for windows 10
best vpn for privacy best free vpn chrome
avast vpn free vpn for streaming buy 911 vpn best free vpn for windows
setting up a vpn express vpn free windows torrent vpn vpn software
free fast vpn cisco vpn what does vpn mean cyberghost vpn free trial
cyberghost vpn free tor free vpn how to get a vpn vpn for windows free download
what is vpn connection download vpn for pc the best
vpn business class vpn
best vpn services 2018 avast secure vpn free vpn download for windows sonicwall vpn client
open source vpn hotspot shield vpn proxy free vpn with free trial best vpn services 2019
cnet best vpn best vpn service review free vpn servers free vpn download
softether vpn client manager best vpn for computer best free unlimited vpn business class vpn
win real money online casino online casino free bonus no
deposit spel online sociala casino win real money
best mobile casino casino sites play casino games for
real money casino online 2023
Can I simply just say what a relief to uncover someone that truly understands what theyre talking about online. You certainly realize how to bring a problem to light and make it important. A lot more people have to check this out and understand this side of your story. I was surprised you arent more popular given that you definitely have the gift.
real casino slots bet online casino casion best casino bonus
online casino reviews usa mobile casino real money online casino games for real money no deposit online casino real money
mobile casino real money online casino wind creek online casino real money online casino with free signup bonus real money usa no deposit
casinos gambling online online casino games win real money casino world free online games online gambling reviews
top online casino play casino world free online no deposit casino real
money real online games for cash
zone online casino free games bon casino casino world free online poker top us online casinos
real money casino bonus play live casino online play casinos online real money casino online
online slots for real money nline casino bonus online slots that pay real money play for real money online casino
very informative articles or reviews at this time.
We stumbled over here different page and thought I might check things out.
I like what I see so now i am following
you. Look forward to looking at your web page again.
big fish free slots games free spins indiana grand slots list vegas world free slot play for fun
slots free casino games no download downloadable slots that pay out video poker free slots
free slots win money instantly real casino free slots konami slots download machine casino gratuite
tadalafil lilly cialis professional cialis original
tadalafil citrate dosage cialis risks walmart pharmacy tadalafil
tadalafil natural substitute cialis payment with paypal cialis paypal accepted
my free vegas slots on facebook free online igt slots casino machine gratuite vegas world
inferno slots login free caesars online casino slots online casino slots real money life of luxury slots
live casino slots lona bonus netbet real casino free slots facebook caesars slots free coins
river slots sweepstakes slot machine games cleopatra gold slots machines online free huge casino slots
free slots home 12345 free caesars slot no download
best free slots real money konami slots for computer
jackpot magic slots blog grand casino slots luckyland slots casino my konami slots free chips
san manuel online casino my free vegas slots on facebook
free slots 777 no download baba casino
Greetings! Very useful advice in this particular article! Its the little changes that will make the biggest changes. Thanks for sharing!
viagra para hombres sildenafil overnight shipping sildenafil de 100 mg
sildenafil teva viagra gel uk viagra near me
cialis uk cialis contraindications cheap tadalafil 20mg
about tadalafil 20mg cialis patent expiration 2016 tadalafil 10mg
tadalafil citrate cialis vs levitra tadalafil order online
amlodipine used for amlodipine besylate 10mg tablets norvasc side effects
atorvastatin tab 20mg lipitor brand atorvastatin 40 mg
buspirone 10 mg buspirone indications buspar dosage
very informative articles or reviews at this time.
Excellent blog post. I certainly love this website. Keep it up!
Good post. I learn something totally new and challenging on blogs I stumbleupon on a daily basis. Its always useful to read content from other authors and practice something from their websites.
trazodone 50 can you buy trazodone in mexico trazodone 100mg pharmacy online
Way cool! Some extremely valid points! I appreciate you writing this article and also
the rest of the website is extremely good.
I just couldn’t depart your website before suggesting that I really enjoyed the standard information an individual supply on your guests?
Is gonna be again frequently to check up on new posts
Everything is very open with a very clear clarification of the challenges.
It was really informative. Your website is extremely helpful.
Many thanks for sharing!
Hey there! Someone in my Myspace group shared this site
with us so I came to look it over. I’m definitely loving the information. I’m book-marking and will be tweeting this to
my followers! Wonderful blog and outstanding design.
Ahaa, its nice conversation on the topic of this paragraph here at this website, I have read all that,
so now me also commenting at this place.
I have been surfing online more than three hours today, yet I never found any interesting article like yours.
It is pretty worth enough for me. In my view, if all site owners and bloggers made good content as you did, the net will be a lot more useful than ever before.
This article will help the internet viewers for building up new blog or even a weblog from
start to end.
I will right away seize your rss feed as I can’t to find your e-mail subscription hyperlink or newsletter service.
Do you’ve any? Kindly allow me realize in order that I could subscribe.
Thanks.
Hi, I do think this is an excellent website. I stumbledupon it 😉 I am going to return once again since i have saved as a favorite it.
Money and freedom is the greatest way to change, may you be rich and continue to guide other people.
dapoxetine buy online usa dapoxetine uk prescription dapoxetine online uk
albuterol 1.25 mg online ventolin buy albuterol tablets online
My doctor told me to avoid taking 1500 mg metformin if I have kidney problems.
Does anyone know where I can buy Accutane cheaply without risking counterfeit products?
reputable online pharmacy uk cheapest pharmacy for prescriptions overseas pharmacy no prescription
budesonide 9 mg tablets price
amoxicillin buy canada
rx budesonide
plavix 75 india cost of plavix in canada plavix clopidogrel
budesonide 0.5
I’ve been surfing online more than 3 hours lately, yet I by no means
found any fascinating article like yours. It’s
beautiful worth sufficient for me. Personally, if all webmasters and bloggers made good content material as you probably did, the web shall be a lot more useful than ever before.
You could definitely see your enthusiasm within the paintings you write. The arena hopes for even more passionate writers like you who are not afraid to say how they believe. All the time follow your heart.
I have been surfing online more than three hours nowadays,
yet I by no means discovered any interesting article like yours.
It is beautiful value sufficient for me. In my view, if all site owners and bloggers made excellent content as
you probably did, the web will probably be much more useful than ever before.
I love what you guys are usually up too. This type of clever
work and exposure! Keep up the amazing works guys I’ve included you guys to my own blogroll.
I will immediately seize your rss as I can’t find your email subscription hyperlink or e-newsletter
service. Do you’ve any? Please permit me know in order that I may just subscribe.
Thanks.
Amazing blog! Do you have any hints for aspiring writers?
I’m planning to start my own blog soon but I’m a little
lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed ..
Any suggestions? Appreciate it!
Thanks for your post. One other thing is when you are promoting your property all on your own, one of the difficulties you need to be conscious of upfront is how to deal with home inspection reviews. As a FSBO supplier, the key concerning successfully switching your property plus saving money in real estate agent commission rates is understanding. The more you already know, the better your sales effort will probably be. One area exactly where this is particularly vital is assessments.
I wanted to create you a very little word to finally say thank you again considering the beautiful knowledge you’ve featured in this case. It is certainly strangely generous of you giving extensively what most of us would have advertised for an e book in making some dough for their own end, even more so now that you could possibly have tried it if you ever decided. Those good ideas likewise worked to be a good way to be certain that the rest have a similar dreams really like my very own to figure out much more with regard to this condition. I am certain there are millions of more fun occasions up front for many who look into your site.
There is definately a great deal to know about this
issue. I really like all of the points you have made.
I want to to thank you for this very good read!! I definitely
loved every little bit of it. I’ve got you bookmarked to check out
new stuff you
sildenafil nz
sildenafil soft tablets 100mg
Make sure to finish the full course of ciprofloxacin 500 mg even if your symptoms improve, to prevent the infection from coming back.
benicar 1252 benicar 40 mg 12.5 mg benicar pharmacy
Upcoming German Bundesliga fixtures and match schedule. Find out when the next football games kick off and the latest results. Due to its high ranking amongst other leagues, the Bundesliga is also awarded with four Champions League and three Europa League places. FC Cologne hosts SC Freiburg in the Bundesliga on Saturday at 9:30 AM ET. SC Paderborn 3, Hansa Rostock 0 Get the upcoming Bundesliga fixtures and check out the latest match schedule. Scan through the list of games to find out when they’re taking place. Hertha Berlin 1-4 Eintracht Frankfurt Germany’s top tier has seen 56 different clubs participate throughout its inception. What’s more, the Bundesliga is also the most attended football league in the world. RB Leipzig continued their strong away run as they defeated Augsburg 2-0 away. The visitors have now gone nine away games without a defeat, with the latest win extending that club record. Despite starting the game slowly, goals from Angelino and Yussuf Poulsen in either half wrapped up a comprehensive victory.
http://epec.or.kr/bbs/board.php?bo_table=free&wr_id=68683
Get us in your feed The Chelsea defender has been heavily linked with a move to Barcelona this summer, with Thomas Tuchel even seeming to confirm that he will leave, but the Blues now appear to be using him as a bargaining chip. Why the former Spurs head coach is an excellent choice for Chelsea However, reports now claim that Jose Mourinho has thrown his hat into the ring after forming a close-bond with the 29-year-old during their time together in the Spanish capital. Graham Potter’s replacement at Chelsea, according to Jacobs’ Caught Offside columnist, Mauricio Pochettino, is in advanced negotiations. The process is advancing quickly, and as of Monday night, final discussions were in progress. Even though a contract hadn’t been issued by Chelsea as of Monday night and it wasn’t quite a done deal, there was genuine optimism on both sides that a deal would be reached.
clonidine coupon
You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
over the counter dapoxetine dapoxetine 30 mg brand name dapoxetine brand in india
flomax for women with kidney stones
I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.
clonidine as a sleep aid
baclofen medicine pills baclofen price south africa baclofen 5 mg tablet
baclofen tablet
celebrex 50 mg capsules
prednisolone prices
accutane medication
synthroid 62 5 mg
strattera 80 mg price
medication trazodone 50 mg
lyrica cost in canada
trazodone price
buy atarax online
prazosin no prescription
buy diflucan for yeast infection
doxycycline capsules 100mg price
propecia 2.5 mg
best canadian pharmacy
metformin where to buy in uk
lexapro 100mg tablets
motilium for sale
vermox tablets nz
100mg prednisolone
I experienced headaches and mood swings with generic metformin.
trustworthy online pharmacy
buy provigil online india
No prescription needed for generic allopurinol 300 mg at Bangs.
aurogra 100 uk
effexor 225 mg cost
effexor 225 mg daily
where to order cialis in canada
valtrex 500mg
zithromax india
price of lasix 80 mg
zithromax 500
silagra 100 price in india
prinivil online
baclofen 832 brand name
generic cialis 5mg online
valtrex pills
how to buy valtrex without a prescription
permethrin cream
buy valtrex without a prescription
zestoretic coupon
propecia prices australia
best albuterol
prednisone 50 mg tablet price
fildena 50 mg price in india
generic zoloft cost
prozac discount
legal canadian pharmacy online
where to get accutane cheap
tadalafil medicine
levitra india generic
synthroid 50 mg tablet