qemu-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: OT: C Q/As, was Re: [Qemu-devel] security_20040618


From: Michael Jennings
Subject: Re: OT: C Q/As, was Re: [Qemu-devel] security_20040618
Date: Mon, 21 Jun 2004 11:44:40 -0400
User-agent: Mutt/1.4.2.1i

On Monday, 21 June 2004, at 10:50:44 (+0200),
Christof Petig wrote:

> can you enlighten me? The only drawback I see is that with plain C
> (no C++) typedef enum { ... } BOOL; would be more appropriate.
> 
> I would propose
> #ifndef __cplusplus
> typedef enum { false, true } bool;
> #endif
> as the optimal solution for a problem I hardly have (since I usually 
> don't go back to coding in C)

There are two problems with using enum's and/or #define's for
TRUE/FALSE.  They should not be used in boolean expressions except
where the return value is of that same typedef (e.g., the function
returns bool) or is generated from the same set of #define's.  While
false is always 0, true is not always 1.  True is non-zero.

> const char *itoa(int i)
> {  char x[20];
>    snprintf(x,sizeof x,"%d",i);
>    return x;
> }

Forgot "static" before char x[20];, or to be more threadsafe, either
malloc() or pass in a buffer and max size.

> defensive programming would require that TRUE be also defined as
> 
> #define TRUE 1
> 
> as many unsuspecting programmers will expect TRUE and FALSE to be handled in
> the preprocessor phase eg:
> 
> #if TRUE
>     ...
>     somecode();
>     ...
> #endif

I disagree strongly.  Anyone who writes "#if TRUE" or "#if FALSE" is
just asking for trouble; (s)he needs to be taught a lesson.  "#if 0"
and "#if 1" are just as obvious, and both "#if 1" and "#if TRUE" are
equally ridiculous.

A better technique would be something more like this:

#define UNUSED_CODE_BLOCK 0

#if UNUSED_CODE_BLOCK
...
#else  /* used code below */
...
#endif

But even then it isn't as clean and readable as 1 or 0.  Plus, you've
still failed to solve the problem that true may or may not be 1.

Michael

-- 
Michael Jennings (a.k.a. KainX)  http://www.kainx.org/  <address@hidden>
n + 1, Inc., http://www.nplus1.net/       Author, Eterm (www.eterm.org)
-----------------------------------------------------------------------
 "You can accomplish much if you don't care who gets the credit."
                                                      -- Ronald Reagan




reply via email to

[Prev in Thread] Current Thread [Next in Thread]