standards/60772: _Bool and bool should be unsigned

Jason Evans jasone at canonware.com
Wed Dec 31 16:50:16 PST 2003


>Number:         60772
>Category:       standards
>Synopsis:       _Bool and bool should be unsigned
>Confidential:   no
>Severity:       serious
>Priority:       high
>Responsible:    freebsd-standards
>State:          open
>Quarter:        
>Keywords:       
>Date-Required:
>Class:          sw-bug
>Submitter-Id:   current-users
>Arrival-Date:   Wed Dec 31 16:50:14 PST 2003
>Closed-Date:
>Last-Modified:
>Originator:     Jason Evans
>Release:        FreeBSD 4.9-RC i386
>Organization:
>Environment:
System: FreeBSD canonware.com 4.9-RC FreeBSD 4.9-RC #12: Fri Oct 17 22:15:36 PDT 2003 jasone at canonware.com:/usr/src/sys/compile/CANONWARE i386


>Description:
	_Bool and bool must be unsigned, so that structure bit fields work as
	expected.
>How-To-Repeat:
#include <stdio.h>
#include <stdbool.h>

/* _Bool and bool must be unsigned.  Otherwise, stucture bit fields do not work
 * correctly, due to how sign extension works. */

struct foo {
	bool white:1; /* Note :1 (bit field). */
};

struct bar {
	bool white:2;
};

int
main(void)
{
	struct foo foo;
	struct bar bar;
	bool white;

	foo.white = false;
	fprintf(stderr, "%u (expect 0)\n", foo.white);
	fprintf(stderr, "%u (expect 1)\n", !foo.white);
	foo.white = !foo.white; /* Breaks. */
	fprintf(stderr, "%u (expect 1)\n", foo.white);
	fprintf(stderr, "%u (expect 0)\n", !foo.white);

	bar.white = false;
	fprintf(stderr, "%u (expect 0)\n", bar.white);
	fprintf(stderr, "%u (expect 1)\n", !bar.white);
	bar.white = !bar.white;
	fprintf(stderr, "%u (expect 1)\n", bar.white);
	fprintf(stderr, "%u (expect 0)\n", !bar.white);

	white = false;
	fprintf(stderr, "%u (expect 0)\n", white);
	fprintf(stderr, "%u (expect 1)\n", !white);
	white = !white;
	fprintf(stderr, "%u (expect 1)\n", white);
	fprintf(stderr, "%u (expect 0)\n", !white);

	return 0;
}

>Fix:
Using bit fields with more than one bit works around the problem, but is
not a satisfactory workaround.  This bug can cause obscure problems, since
something like:

	if (foo.white == true) ...;

breaks.
>Release-Note:
>Audit-Trail:
>Unformatted:


More information about the freebsd-standards mailing list