☰
Current Page
Main Menu
Home
Home
Editing
BitfieldGotchas
Edit
Preview
h1
h2
h3
Keybinding
default
vim
emacs
Markup
Markdown
Plain Text
Pod
RDoc
reStructuredText
AsciiDoc
BibTeX
Creole
MediaWiki
Org-mode
Textile
Help 1
Help 1
Help 1
Help 2
Help 3
Help 4
Help 5
Help 6
Help 7
Help 8
Autosaved text is available. Click the button to restore it.
Restore Text
--- title: BitfieldGotchas --- # Assignment from Fake Boolean In the following example a boolean flag is passed across an interface. * In the source object, flags were implemented using an enum. * In the destination object they were implemented as a bitfield. * The bug was hidden by the use of a C89-style typedeffed BOOL (an int) The resulting code fails to assign the boolean flag correctly. The bug is a non-issue if C99 stdbool is used instead. ## Source #include <stdio.h> //printf #if \_\_STDC\_VERSION\\_\_ >= 199901 # include <stdbool.h> typedef _Bool BOOL; # define FALSE false #else /* C89 Fake bool */ typedef int BOOL; # define FALSE (0) #endif /* Source data */ enum EFLAGS { FLAG_NONE = 0x00, FLAG_FOO = 0x01, FLAG_BAR = 0x02, FLAG_MAX } srcFlags = FLAG_NONE; struct SFLAGS { int isFoo :1; int isBar :1; } dstFlags = {, }; int main(void) { BOOL tmpBool = FALSE; srcFlags |= FLAG_BAR; /* set BAR in src */ tmpBool = (srcFlags & FLAG_BAR); /* pass in BOOL */ /* fake BOOL: tmpBool has value 2 * C99 _Bool: tmpBool has value true */ dstFlags.isBar = tmpBool; /* set in dst */ /* fake BOOL: isBar is assigned (2 & 0x01) = 0 !!! * C99 _Bool: isBar is assigned true */ if (dstFlags.isBar) { printf("dstFlags.isBar is TRUE"); } else { printf("dstFlags.isBar is FALSE"); } return ; } ## Results $ gcc -std=c89 -pedantic -Wall -o bitfield1 bitfield1.c && ./bitfield1 dstFlags.isBar is FALSE $ gcc -std=c99 -pedantic -Wall -o bitfield1 bitfield1.c && ./bitfield1 dstFlags.isBar is TRUE ## Lesson * Always sanitise fake BOOL with !!(x) or (x != 0) * Or avoid the problem entirely by using C99 _Bool [1]: BitfieldGotchas?action=sourceblock&num=1
Uploading file...
Sidebar
# SideBar * [Home][1] * [Projects][2] * * * <!-- --> * [Code][3] * [Tech][4] * [Network][5] * [MediaCentre][6] * [UAV][7] * * * <!-- --> * [Travel][8] * [Music][9] * [Horse Riding][10] * [Study][11] * [Games][12] * [Other Activities][13] * * * <!-- --> * [Car][14] * [House][15] * [Watch][16] * [Clothing][17] * [Miscellany][18] * * * [1]: /Home [2]: /Projects [3]: /Code/Code [4]: /Tech/Tech [5]: /Network/Network [6]: /MediaCentre/MediaCentre [7]: /UAV/UAV [8]: /Travel/Travel [9]: /Music/Music [10]: /HorseRiding/HorseRiding [11]: /Study/Study [12]: /Games/Games [13]: /Do/Do [14]: /Car/Car [15]: /House/House [16]: /Watch/Watch [17]: /Clothing/Clothing [18]: /Miscellany/Miscellany
Edit message:
Cancel