Re: [dev] Learn C

From: David Demelier <markand_AT_malikania.fr>
Date: Mon, 1 Apr 2019 10:15:46 +0200

Le 24/03/2019 à 14:33, sylvain.bertrand_AT_gmail.com a écrit :
> * do not use enum (hard rule)

I'd be glad to get any reason why not. C is already minimalistic, won't
you write in assembly next time?

Moreover, enums are often well supported in debuggers and show the
actual enum constant rather than its value. Also, compilers are smart
enough to be sure you compare good things:

$ gcc test.c -Wall -Wextra
test.c: In function ‘main’:
test.c:8:8: warning: comparison between ‘enum gender’ and ‘enum color’
[-Wenum-compare]
   if (g == red)
         ^
$ cat test.c
enum gender { male, female };
enum color { red, green, blue };

int main()
{
         enum gender g = male;

         if (g == red)
                 return 1;
}

> * declare your variables at the beginning of a block (c99 allows declarations a
> bit everywhere, bad). personnally I try to keep my variables declared first, then
> the variables with assignment, because it's actually code (presume C
> initializers are code).

Welcome to prehistory. Declaring when you use (with a assignment) makes
uninitialized variables less often happening.

> * I personnaly add a macro #define loop for(;;) and use only 1 loop
> statement (hard rule)

Strange, hiding explicit code for a benefit of 4 keystrokes.

> * use sized types: u8 u16 i64 float32 etc... you can use the C
> preprocessor to fix that, but in some case, as a good tradeof (for instance in
> "object oriented C code"), add a suffix to your type (u8_t, struct my_class_t), then
> for instance you can nest structs, struct base_type_t base_type.

This is completely nonsense. Do you know that using the appropriate
types is just the best thing to do? For example, it's sometimes even
better to pass an int rather than a bool as argument/return value
because the processor has to perform more steps since it will promotes
the bool to int. In most of the case int is just the way to go. However,
having those fixed size types in PODs for serialization, hardware access
and memory management is clean (but with care of alignment/padding).

Regards,

-- 
David
Received on Mon Apr 01 2019 - 10:15:46 CEST

This archive was generated by hypermail 2.3.0 : Mon Apr 01 2019 - 12:00:08 CEST