SlideShare une entreprise Scribd logo
1  sur  36
Télécharger pour lire hors ligne
1




                Advanced
C Foundation




               Techniques
2       • code that compiles in both C and C++
               C++ compiler is stricter than C
               e.g. pre C99 did not require function declarations
               e.g. C++ requires more conversions to be explicit
               avoid C++ keywords
                      bool             new                 typeid
                      catch            operator            typename
                      class            private             using
                      const_cast       protected           virtual
                      delete           public              wchar_t
                      dynamic_cast     reinterpret_cast
                      explicit         static_cast
clean C




                      export           template
                      false            this
                      friend           throw
                      mutable          true
                      namespace        try

                      C++ keywords that are not also C keywords
3       • Comments can indicate missing code

                               BEFORE
            void test_is_leap_year(void)
            {
                // years not divisible by 4 are leap years
                assert(is_leap_year(1906));
                assert(!is_leap_year(2009));

                // years divisible by 4 but not 100 are leap years
comments




                assert(is_leap_year(1984));
                assert(is_leap_year(2008));

                // years divisible by 100 but not 400 are not leap years
                assert(!is_leap_year(1900));
                assert(!is_leap_year(2100));

                // years divisible by 400 are leap years
                assert(is_leap_year(2000));
                assert(is_leap_year(2400));
            }
4       • Imagine if C had no comments

                                AFTER
           void years_not_divisible_by_4_are_leap_years(void)
           {
               assert(is_leap_year(1906));
               assert(!is_leap_year(2009));
           }
           void years_divisible_by_4_but_not_100_are_leap_years(void)
           {
               assert(is_leap_year(1984));
comments




               assert(is_leap_year(2008));
           }
           void years_divisible_by_100_but_not_400_are_not_leap_years(void)
           {
               assert(!is_leap_year(1900));
               assert(!is_leap_year(2100));
           }
           void years_divisible_by _400_are_leap_years(void)
           {
               assert(is_leap_year(2000));
               assert(is_leap_year(2400));
           }
5             • prefer initialization to assignment


                      refactor
                                 int count;
                                 count = 0;                    ?
                                                               
clarity ~ brevity


                                 int count = 0;



                    • don't explicitly compare against true/false



                      refactor
                                    if (has_prefix("is") == true)
                                        ...
                                                                    ?
                                    if (has_prefix("is"))
                                        ...
                                                                    
6              • avoid redundant use of true/false

                              this version is very "solution focused"
implicit vs explict
                              bool is_even(int value)
                              {
                                  if (value % 2 == 0)

                                  else
                                       return true;                     ?
                                       return false;
                              }



                              this version is less solution focused;    refactor
                              it is more problem focused;
                              it is more "declarative"
                              bool is_even(int value)
                              {

                              }
                                  return value % 2 == 0;                
7              • make inter-statement dependencies explicit

                            consider if you accidentally refactor the if without
                            the last return - oops
implicit vs explict

                            bool some_func(int value)
                            {
                                if (value % 2 == 0)
                                    return alpha();
                                return beta();
                                                                     ?
                            }




                            the return statements are now at the              refactor
                            same indentation. logical == physical
                            bool some_func(int value)
                            {


                                                                     
                                if (value % 2 == 0)
                                    return alpha();
                                else
                                    return beta();
                            }
8            • in general, beware of boolean literals

                      again, wordy, verbose


                           if (oldest)
logic vs control

                               if (last_access < cut_off)


                                                                    ?
                                    return true;
                               else
                                    return false;
                           else
                               return false;



                      much simpler, reads well
                                                            refactor

                          return oldest && last_access < cut_off;
                                                                    
9           • iteration is a common bug hotspot
                    looping is easy, knowing when to stop is tricky!
                 • follow the fundamental rule of design
                    always design a thing by considering it in its next
                     largest context
                    what do you want to be true after the iteration?
how to iterate



                    this forms the termination condition
                      ... search(size_t end, int values[], int find)
                      {
                          size_t at = 0;
                              // values[at==0  at==end] iteration
                              at == end         ||     values[at] == find
                              ...
                      }


                          we didn't find it............ or ....................we found it
                                               (short-circuiting)
10           • the negation of the termination condition is
                   the iteration's continuation condition
                    !(at == end || values[at] == find)
                                                                equivalent
                    at != end && values[at] != find            (DeMorgan's Law)


                     ... search(size_t end, int values[], int find)
how to iterate


                     {
                         size_t at = 0;
                         while (at != end && values[at] != find)
                         {
                             ...
                         }
                         ...
                     }



                             at++;             short-circuiting protects values[at]


                 • then simply fill in the loop body
                                                               
11         • don't attempt to hide a pointer in a typedef
                 if it's a pointer make it look like a pointer
                 abstraction is about hiding unimportant details


                  date.h
                  typedef struct date * date;
                                                         ?
bad typedef



                  bool date_equal(const date lhs, const date rhs);

                  what is const?

                  bool date_equal(const struct date * lhs,
                                  const struct date * rhs);
                  is it the date object pointed to?
                  bool date_equal(struct date * const lhs,
                                  struct date * const rhs);
                  or is it the pointer?
12




               date.h
                                            no * here
                                                        
               typedef struct date date;

               bool date_equal(const date * lhs,
good typedef


                               const date * rhs);


                                                        alternatives
               date.h

               struct date;

               bool date_equal(const struct date * lhs,
                               const struct date * rhs);
13           • a typedef does not create a new type
                       typedef int mile;
                       typedef int kilometer;

                       void weak(mile lhs, kilometer rhs)


                                                                  
                       {
strong typedef


                           lhs = rhs;
                           ...
                       }

                 • consider using a wrapper type instead…
                       typedef struct { int value; } mile;
                       typedef struct { int value; } kilometer;

                       void strong(mile lhs, kilometer rhs)
                       {

                       }
                           lhs = rhs;
                                                                  
14        • enums are very weakly typed
               an enum's enumerators are of type integer, not of
                the enum type itself!

                 typedef enum
                 {
                     clubs, diamonds, hearts, spades
                 } suit;
weak enum




                 typedef enum
                 {
                     spring, summer, autumn, winter
                 } season;

                 void weak(void)
                 {

                 }
                     suit trumps = winter;
                                                       
15           suit.h
                 typedef struct { int value; } suit;
                 extern const suit clubs, diamonds, hearts, spades;
                 season.h
                 typedef struct { int value; } season;
                 extern const season spring, summer, autumn, winter;
stronger enums



                 void strong(void)
                 {

                 }
                     suit trumps = winter;
                                                     
                                        const suit clubs      =   {   0   },
                 season.c
                                                   diamonds   =   {   1   },
                 const season spring   = { 0 },    hearts     =   {   2   },
                              summer   = { 1 },    spades     =   {   3   };
                              autumn   = { 2 },
                              winter   = { 3 };                           suit.c
16          • 5.1.2.3 Program semantics
                  At certain specified points in the execution
                   sequence called sequence points,
                     all side effects of previous evaluations shall be
                      complete and
                     no side effects of subsequent evaluations
                      shall have taken place
               • what constitutes a side effect?
side effects




                    accessing a volatile object
                    modifying an object
                    modifying a file
                    calling a function that does any of these
17       • 6.7.3 Type qualifiers
              An object that has volatile-qualified type may be
               modified in ways unknown to the implementation
               or have other unknown side effects. Therefore
               any expression referring to such an object shall
               be evaluated strictly according to the rules…
               described in 5.1.2.3

             int global;                 reg looks unchanged but reg is
             volatile int reg;           volatile so an access to the object
             ...                         is required. This access may cause
                 reg *= 1;               its value to change.
volatile




                   reg = global;         these cannot be optimized to a
                   reg = global;         single assignment.

                   int v1 = reg;         v1 might not equal v2.
                   int v2 = reg;
             ...
18
           • in this statement…
              where are the sequence points?
              where are the side-effects?
              is it undefined?



               volatile int m;

               void eg(void)
exercise




               {
                   int value = m + m;
                   ...
               }
19          • #include dependencies are transitive
                  if you change a .h file you have to recompile all
                   files that #include it at any depth
                  a visible reflection of the physical coupling
                 wibble_t.h                                    sink.h
dependencies


                 #include "grommit.h"    grommit.h
                 #include "flange.h"
                 ...                     #include "sink.h"
                 typedef struct          #include "washer.h"
                 {                       ...
                     grommit w;          typedef struct
                     flange f;           {
                     ...                      sink dest;       washer.h
                 } wibble_t;                  washer w;
                                             ...
                              flange.h   } grommit;
20          • an ADT implementation technique
                   a forward declaration gives the name of a type
                   the definition of the type – and it's accompanying
                    #includes – are not specified in the header
                   all use of the type has to be as a pointer and all
                    use of the pointer variable has to be via a function
opaque types



                wibble.h
                ...                                       minimal #includes
                typedef struct wibble_tag wibble;

                                                          not defined
                wibble * wopen(const char * filename);
                                                         all uses of wibble
                int wclose(wibble * stream);             have to be
                ...                                      as pointers
21          • in most APIs the idea that a set of functions
                 are closely related is quite weakly expressed
                     int main(int argc, char * argv[])
                     {
                         wibble * w = wopen(argv[1]);
                         ...
                         wclose(w);
                     }
module : use



               • a struct containing function pointers can
                 express the idea more strongly
                     int main(int argc, char * argv[])
                     {
                         wibble * w = wibbles.open(argv[1]);
                         ...
                         wibbles.close(w);
                     }
22


                  wibble.h
                  #ifndef WIBBLE_INCLUDED
                  #define WIBBLE_INCLUDED
                  ...
module : header

                  ...
                  typedef struct wibble_tag wibble;

                  struct wibble_api
                  {
                      wibble * (*open )(const char *);
                      ...
                      int (*close)(wibble *);
                  };
                  extern const struct wibble_api wibbles;

                  #endif
23

                  wibble.c
                  #include "wibble.h"
                  ...
                  ...
module : source

                  static                              static linkage
                  wibble * open(const char * name)
                  {    ...
                  }
                  ...
                  static
                  int close(wibble * stream)          no need to write
                  {    ...                            &open, &close
                  };
                  const struct wibble_api wibbles =
                  {
                      open, ..., close
                  };
24    • opaque type memory management…
         clients cannot create objects since they don't
          know how many bytes they occupy
         wibble.h
          ...
          typedef struct wibble wibble;
          ...

          #include "wibble.h"

          void client(void)
          {
              wibble * pointer;
              ...
                                             
                                             
              wibble value;
ADT




              ...
              ptr = malloc(sizeof(*ptr));
          }
25            • an ADT can declare its size!
                      clients can now allocate the memory
                      true representation remains abstract
                                                               
shadow data type

                        wibble.h
                         typedef struct wibble
                         {
                             unsigned char size[16];
                         } wibble;

                         bool wopen(wibble *, const char *);
                         void wclose(wibble *);

                         #include "wibble.h"
                         void client(const char * name)
                         {
                            wibble w;
                            if (wopen(&w, name))


                         }
                               ...
                            wclose(&w);                        
26          • implementation needs to…
                   define the true representation type
                                                       wibble.c

                             the analogy is that the   #include "grommit.h"
                             true type casts           #include "flange.h"
shadowed type


                             a shadow which
                             reveals only its size     typedef struct
                                                       {
                                                           grommit g;
                                                           flange f;
                                                           ...
                                                       } wibble_rep;


                  wibble.h
                  typedef struct wibble
                  {
                      unsigned char size[16];
                                                                             
                  } wibble;                                       Still some problems
                                                                  though…
27        • the size of the type must not be smaller than
              the size of the type it shadows
               assert only works at runtime
               it would be safer to check at compile time


               wibble.h                   wibble.c
               typedef struct wibble       typedef struct
               {                           {
problem 1




                   ...                         ...
               } wibble;                   } wibble_rep;




               assert(sizeof(wibble) >= sizeof(wibble_rep))



                                                
28        • use a compile time assertion
                you cannot declare an array with negative size

                compile_time_assert.h
                #define COMPILE_TIME_ASSERT(desc,exp) ¬
                              extern char desc [ (exp) ? 1 : -1 ]



                                                      
                #include "compile_time_assert.h"
                COMPILE_TIME_ASSERT(ok, 1 == 1);
deep magic




                #include "compile_time_assert.h"
                COMPILE_TIME_ASSERT(
                    your_message,
                    1 == 0);
                                                      
                    gcc
                      error: size of array 'your_message' is negative
29
                  wibble.c
                  #include   "wibble.h"
                  #include   "flange.h"
                  #include   "grommet.h"
                  #include   "compile_time_assert.h"
compatible size


                  typedef struct
                  {
                      grommet g;
                      flange f;
                  } wibble_rep;

                  COMPILE_TIME_ASSERT(
                      sizeof_wibble_not_less_than_sizeof_wibble_rep,
                      sizeof(wibble) >= sizeof(wibble_rep));
                  ...




                                                     
30        • the two types must be alignment compatible
               this means the first member of both types must be
                alignment compatible
                  wibble.h
                  typedef struct wibble
                  {
                      unsigned char size[16];
                  } wibble;
problem 2




                 wibble.c
                 typedef struct
                 {
                     grommit g;
                                                  
                     flange f;
                     ...
                 } wibble_rep;
31              • use a union to force alignment
                      alignment.h
                      typedef union
alignment solution
                      {
                          char c,*cp; int i,*ip; long l,*lp; long long ll,*llp;
                          float f,*fp; double d,*dp; long double ld,*ldp;
                          void *vp;
                          void (*fv)(void); void (*fo)(); void (*fe)(int,...);
                      } alignment;

                     wibble.h
                                                      List all the primitive types in here.
                      #include "alignment.h"
                                                      One must have the strictest alignment
                      ...
                      typedef union wibble
                      {
                          alignment universal;
                          unsigned char size[16];
                      } wibble;
                                                           
                      ...
32        • unions are much rarer than structs
               design is as much about use as implementation

                                                forward declaration
                  client.h


                  typedef struct wibble wibble;
                  ...



                                                                 
problem 3




                             Oooops: it's a union not a struct

               6.7.2.3 Tags
                Paragraph 1, sentence 2
                Where two declarators that use the same tag declare
                the same type, they shall both use the same choice
                of struct, union, or enum.
33           • put a union object inside a struct!
                    drop the union tag name
                   wibble.h
                    ...
                    typedef struct wibble
                                                       
                    {
wrapper struct


                        union
                        {
                            alignment universal;
                            unsigned char size[16];
                        } shadow;                      one object
                    } wibble;
                    ...

                    6.7.2.3 Tags
                     Paragraph 4, sentence 2
                     Each declaration of a structure, union, or
                     enumerated type which does not include a tag
                     declares a distinct type
34          • conversion can be via memcpy
                   helper function allows assignment

                  wibble.c                               
                  wibble.c inline wibble shadow(wibble_rep * src)
                  static
                  {
conversions 1


                        wibble dst;
                        memcpy(&dst, src, sizeof(*src));
                        return dst;
                  }

                  bool wopen(wibble * w, const char * name)
                  {
                      wibble_rep rep = {
                         .g = ...,
                         .f = ...,
                      };
                      *w = shadow(&rep);
                      ...;
                  }
35          • conversion can be via pointer casts
                   helper function allows  operator


                    wibble.c                            
                    static inline wibble_rep * rep(wibble * w)
conversions 2


                    {
                        return (wibble_rep *)w;
                    }

                    void wclose(wibble * w);
                    {
                        rep(w)->g = ...;
                        rep(w)->f = ...;
                        ...
                    }
36     • This course was written by



               Expertise: Agility, Process, OO, Patterns
               Training+Designing+Consulting+Mentoring
                                                           { JSL }

                         Jon Jagger
                                    jon@ jaggersoft.com
Contact




                                     www.jaggersoft.com

Contenu connexe

Tendances

Micro Blaze C Reference
Micro Blaze C ReferenceMicro Blaze C Reference
Micro Blaze C Referenceiuui
 
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...DrupalMumbai
 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inTIB Academy
 
Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)chk49
 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer TutorialsNont Banditwong
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1karmuhtam
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3 rohassanie
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 

Tendances (19)

Micro Blaze C Reference
Micro Blaze C ReferenceMicro Blaze C Reference
Micro Blaze C Reference
 
C++ functions
C++ functionsC++ functions
C++ functions
 
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Perl slid
Perl slidPerl slid
Perl slid
 
Lecture1
Lecture1Lecture1
Lecture1
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.in
 
JSTLQuick Reference
JSTLQuick ReferenceJSTLQuick Reference
JSTLQuick Reference
 
Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)
 
C# slid
C# slidC# slid
C# slid
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
L05if
L05ifL05if
L05if
 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer Tutorials
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 

En vedette

DIRECCIONAR UNA EMPRESA CON FLUJO GRAMAS
DIRECCIONAR UNA EMPRESA CON FLUJO GRAMASDIRECCIONAR UNA EMPRESA CON FLUJO GRAMAS
DIRECCIONAR UNA EMPRESA CON FLUJO GRAMASeva lucero oquendo
 
Procesos de venta
Procesos de ventaProcesos de venta
Procesos de ventacolonia8
 
Casos frecuentes de no conformidades en obra civil
Casos frecuentes de no conformidades en obra civilCasos frecuentes de no conformidades en obra civil
Casos frecuentes de no conformidades en obra civildavidmm30
 
Plan de produccion
Plan de produccionPlan de produccion
Plan de produccionJhonson Q M
 
Pasos para realizar la trazabilidad de una obra
Pasos para realizar la trazabilidad de una obraPasos para realizar la trazabilidad de una obra
Pasos para realizar la trazabilidad de una obradavidmm30
 
Empresa constructora
Empresa constructoraEmpresa constructora
Empresa constructorablehirmen
 
Gestión de la calidad en las empresas constructoras
Gestión de la calidad en las empresas constructorasGestión de la calidad en las empresas constructoras
Gestión de la calidad en las empresas constructorasxkiraz
 
Las 7 claves para gestionar de forma eficaz la calidad en obra
Las 7 claves para gestionar de forma eficaz la calidad en obraLas 7 claves para gestionar de forma eficaz la calidad en obra
Las 7 claves para gestionar de forma eficaz la calidad en obradavidmm30
 
Diagrama de-flujo-de-bloques
Diagrama de-flujo-de-bloquesDiagrama de-flujo-de-bloques
Diagrama de-flujo-de-bloquesRonald Collado
 
Mapa conceptual empresa constructora- franklin salaya 23.897.476
Mapa conceptual  empresa constructora- franklin salaya 23.897.476Mapa conceptual  empresa constructora- franklin salaya 23.897.476
Mapa conceptual empresa constructora- franklin salaya 23.897.476franklin salaya
 
Mapa conceptual empresa constructora
Mapa conceptual empresa constructoraMapa conceptual empresa constructora
Mapa conceptual empresa constructoramarianela perdomo
 
Guia elaboracion-diagramas-flujo-2009
Guia elaboracion-diagramas-flujo-2009Guia elaboracion-diagramas-flujo-2009
Guia elaboracion-diagramas-flujo-2009AxePal
 
Empresas constructoras 03-06_2014
Empresas constructoras 03-06_2014Empresas constructoras 03-06_2014
Empresas constructoras 03-06_2014Alex Cardenas
 
Economía de la Empresa 2º Bachillerato - UD3. Producción empresa I
Economía de la Empresa 2º Bachillerato - UD3. Producción empresa IEconomía de la Empresa 2º Bachillerato - UD3. Producción empresa I
Economía de la Empresa 2º Bachillerato - UD3. Producción empresa IBea Hervella
 
Mirol ERP Constructoras
Mirol ERP ConstructorasMirol ERP Constructoras
Mirol ERP ConstructorasMirol SyS
 

En vedette (20)

Ud2 el proceso productivo
Ud2 el proceso productivoUd2 el proceso productivo
Ud2 el proceso productivo
 
UD2 el proceso productivo
UD2 el proceso productivoUD2 el proceso productivo
UD2 el proceso productivo
 
DIRECCIONAR UNA EMPRESA CON FLUJO GRAMAS
DIRECCIONAR UNA EMPRESA CON FLUJO GRAMASDIRECCIONAR UNA EMPRESA CON FLUJO GRAMAS
DIRECCIONAR UNA EMPRESA CON FLUJO GRAMAS
 
Producción
ProducciónProducción
Producción
 
Procesos de venta
Procesos de ventaProcesos de venta
Procesos de venta
 
Casos frecuentes de no conformidades en obra civil
Casos frecuentes de no conformidades en obra civilCasos frecuentes de no conformidades en obra civil
Casos frecuentes de no conformidades en obra civil
 
Plan de produccion
Plan de produccionPlan de produccion
Plan de produccion
 
Pasos para realizar la trazabilidad de una obra
Pasos para realizar la trazabilidad de una obraPasos para realizar la trazabilidad de una obra
Pasos para realizar la trazabilidad de una obra
 
Empresa constructora
Empresa constructoraEmpresa constructora
Empresa constructora
 
Adrian
AdrianAdrian
Adrian
 
Gestión de la calidad en las empresas constructoras
Gestión de la calidad en las empresas constructorasGestión de la calidad en las empresas constructoras
Gestión de la calidad en las empresas constructoras
 
Las 7 claves para gestionar de forma eficaz la calidad en obra
Las 7 claves para gestionar de forma eficaz la calidad en obraLas 7 claves para gestionar de forma eficaz la calidad en obra
Las 7 claves para gestionar de forma eficaz la calidad en obra
 
Diagrama de-flujo-de-bloques
Diagrama de-flujo-de-bloquesDiagrama de-flujo-de-bloques
Diagrama de-flujo-de-bloques
 
Mapa conceptual empresa constructora- franklin salaya 23.897.476
Mapa conceptual  empresa constructora- franklin salaya 23.897.476Mapa conceptual  empresa constructora- franklin salaya 23.897.476
Mapa conceptual empresa constructora- franklin salaya 23.897.476
 
Mapa conceptual empresa constructora
Mapa conceptual empresa constructoraMapa conceptual empresa constructora
Mapa conceptual empresa constructora
 
Guia elaboracion-diagramas-flujo-2009
Guia elaboracion-diagramas-flujo-2009Guia elaboracion-diagramas-flujo-2009
Guia elaboracion-diagramas-flujo-2009
 
Plan de ventas y operaciones (S&OP)
Plan de ventas y operaciones (S&OP)Plan de ventas y operaciones (S&OP)
Plan de ventas y operaciones (S&OP)
 
Empresas constructoras 03-06_2014
Empresas constructoras 03-06_2014Empresas constructoras 03-06_2014
Empresas constructoras 03-06_2014
 
Economía de la Empresa 2º Bachillerato - UD3. Producción empresa I
Economía de la Empresa 2º Bachillerato - UD3. Producción empresa IEconomía de la Empresa 2º Bachillerato - UD3. Producción empresa I
Economía de la Empresa 2º Bachillerato - UD3. Producción empresa I
 
Mirol ERP Constructoras
Mirol ERP ConstructorasMirol ERP Constructoras
Mirol ERP Constructoras
 

Similaire à 08 advanced techniques

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Embedded systems
Embedded systemsEmbedded systems
Embedded systemsMitul Tank
 
Java Reference
Java ReferenceJava Reference
Java Referencekhoj4u
 
Mysterious c++
Mysterious c++Mysterious c++
Mysterious c++xprayc
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
C statements (a fraction).pptx
C statements (a fraction).pptxC statements (a fraction).pptx
C statements (a fraction).pptxMehrinFarjana
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalQA or the Highway
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingestorebackupr
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle ScalaSlim Ouertani
 
Recursion
RecursionRecursion
RecursionNikxjon
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Coen De Roover
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Victor Rentea
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingMario Fusco
 

Similaire à 08 advanced techniques (17)

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Embedded systems
Embedded systemsEmbedded systems
Embedded systems
 
Java Reference
Java ReferenceJava Reference
Java Reference
 
Mysterious c++
Mysterious c++Mysterious c++
Mysterious c++
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
C statements (a fraction).pptx
C statements (a fraction).pptxC statements (a fraction).pptx
C statements (a fraction).pptx
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert Fornal
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
Recursion
RecursionRecursion
Recursion
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Decision control
Decision controlDecision control
Decision control
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 

Dernier

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 

Dernier (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 

08 advanced techniques

  • 1. 1 Advanced C Foundation Techniques
  • 2. 2 • code that compiles in both C and C++  C++ compiler is stricter than C  e.g. pre C99 did not require function declarations  e.g. C++ requires more conversions to be explicit  avoid C++ keywords bool new typeid catch operator typename class private using const_cast protected virtual delete public wchar_t dynamic_cast reinterpret_cast explicit static_cast clean C export template false this friend throw mutable true namespace try C++ keywords that are not also C keywords
  • 3. 3 • Comments can indicate missing code BEFORE void test_is_leap_year(void) { // years not divisible by 4 are leap years assert(is_leap_year(1906)); assert(!is_leap_year(2009)); // years divisible by 4 but not 100 are leap years comments assert(is_leap_year(1984)); assert(is_leap_year(2008)); // years divisible by 100 but not 400 are not leap years assert(!is_leap_year(1900)); assert(!is_leap_year(2100)); // years divisible by 400 are leap years assert(is_leap_year(2000)); assert(is_leap_year(2400)); }
  • 4. 4 • Imagine if C had no comments AFTER void years_not_divisible_by_4_are_leap_years(void) { assert(is_leap_year(1906)); assert(!is_leap_year(2009)); } void years_divisible_by_4_but_not_100_are_leap_years(void) { assert(is_leap_year(1984)); comments assert(is_leap_year(2008)); } void years_divisible_by_100_but_not_400_are_not_leap_years(void) { assert(!is_leap_year(1900)); assert(!is_leap_year(2100)); } void years_divisible_by _400_are_leap_years(void) { assert(is_leap_year(2000)); assert(is_leap_year(2400)); }
  • 5. 5 • prefer initialization to assignment refactor int count; count = 0; ?  clarity ~ brevity int count = 0; • don't explicitly compare against true/false refactor if (has_prefix("is") == true) ... ? if (has_prefix("is")) ... 
  • 6. 6 • avoid redundant use of true/false this version is very "solution focused" implicit vs explict bool is_even(int value) { if (value % 2 == 0) else return true; ? return false; } this version is less solution focused; refactor it is more problem focused; it is more "declarative" bool is_even(int value) { } return value % 2 == 0; 
  • 7. 7 • make inter-statement dependencies explicit consider if you accidentally refactor the if without the last return - oops implicit vs explict bool some_func(int value) { if (value % 2 == 0) return alpha(); return beta(); ? } the return statements are now at the refactor same indentation. logical == physical bool some_func(int value) {  if (value % 2 == 0) return alpha(); else return beta(); }
  • 8. 8 • in general, beware of boolean literals again, wordy, verbose if (oldest) logic vs control if (last_access < cut_off) ? return true; else return false; else return false; much simpler, reads well refactor return oldest && last_access < cut_off; 
  • 9. 9 • iteration is a common bug hotspot  looping is easy, knowing when to stop is tricky! • follow the fundamental rule of design  always design a thing by considering it in its next largest context  what do you want to be true after the iteration? how to iterate  this forms the termination condition ... search(size_t end, int values[], int find) { size_t at = 0; // values[at==0  at==end] iteration at == end || values[at] == find ... } we didn't find it............ or ....................we found it (short-circuiting)
  • 10. 10 • the negation of the termination condition is the iteration's continuation condition  !(at == end || values[at] == find) equivalent  at != end && values[at] != find (DeMorgan's Law) ... search(size_t end, int values[], int find) how to iterate { size_t at = 0; while (at != end && values[at] != find) { ... } ... } at++; short-circuiting protects values[at] • then simply fill in the loop body 
  • 11. 11 • don't attempt to hide a pointer in a typedef  if it's a pointer make it look like a pointer  abstraction is about hiding unimportant details date.h typedef struct date * date; ? bad typedef bool date_equal(const date lhs, const date rhs); what is const? bool date_equal(const struct date * lhs, const struct date * rhs); is it the date object pointed to? bool date_equal(struct date * const lhs, struct date * const rhs); or is it the pointer?
  • 12. 12 date.h no * here  typedef struct date date; bool date_equal(const date * lhs, good typedef const date * rhs); alternatives date.h struct date; bool date_equal(const struct date * lhs, const struct date * rhs);
  • 13. 13 • a typedef does not create a new type typedef int mile; typedef int kilometer; void weak(mile lhs, kilometer rhs)  { strong typedef lhs = rhs; ... } • consider using a wrapper type instead… typedef struct { int value; } mile; typedef struct { int value; } kilometer; void strong(mile lhs, kilometer rhs) { } lhs = rhs; 
  • 14. 14 • enums are very weakly typed  an enum's enumerators are of type integer, not of the enum type itself! typedef enum { clubs, diamonds, hearts, spades } suit; weak enum typedef enum { spring, summer, autumn, winter } season; void weak(void) { } suit trumps = winter; 
  • 15. 15 suit.h typedef struct { int value; } suit; extern const suit clubs, diamonds, hearts, spades; season.h typedef struct { int value; } season; extern const season spring, summer, autumn, winter; stronger enums void strong(void) { } suit trumps = winter;  const suit clubs = { 0 }, season.c diamonds = { 1 }, const season spring = { 0 }, hearts = { 2 }, summer = { 1 }, spades = { 3 }; autumn = { 2 }, winter = { 3 }; suit.c
  • 16. 16 • 5.1.2.3 Program semantics  At certain specified points in the execution sequence called sequence points,  all side effects of previous evaluations shall be complete and  no side effects of subsequent evaluations shall have taken place • what constitutes a side effect? side effects  accessing a volatile object  modifying an object  modifying a file  calling a function that does any of these
  • 17. 17 • 6.7.3 Type qualifiers  An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Therefore any expression referring to such an object shall be evaluated strictly according to the rules… described in 5.1.2.3 int global; reg looks unchanged but reg is volatile int reg; volatile so an access to the object ... is required. This access may cause reg *= 1; its value to change. volatile reg = global; these cannot be optimized to a reg = global; single assignment. int v1 = reg; v1 might not equal v2. int v2 = reg; ...
  • 18. 18 • in this statement…  where are the sequence points?  where are the side-effects?  is it undefined? volatile int m; void eg(void) exercise { int value = m + m; ... }
  • 19. 19 • #include dependencies are transitive  if you change a .h file you have to recompile all files that #include it at any depth  a visible reflection of the physical coupling wibble_t.h sink.h dependencies #include "grommit.h" grommit.h #include "flange.h" ... #include "sink.h" typedef struct #include "washer.h" { ... grommit w; typedef struct flange f; { ... sink dest; washer.h } wibble_t; washer w; ... flange.h } grommit;
  • 20. 20 • an ADT implementation technique  a forward declaration gives the name of a type  the definition of the type – and it's accompanying #includes – are not specified in the header  all use of the type has to be as a pointer and all use of the pointer variable has to be via a function opaque types wibble.h ... minimal #includes typedef struct wibble_tag wibble; not defined wibble * wopen(const char * filename); all uses of wibble int wclose(wibble * stream); have to be ... as pointers
  • 21. 21 • in most APIs the idea that a set of functions are closely related is quite weakly expressed int main(int argc, char * argv[]) { wibble * w = wopen(argv[1]); ... wclose(w); } module : use • a struct containing function pointers can express the idea more strongly int main(int argc, char * argv[]) { wibble * w = wibbles.open(argv[1]); ... wibbles.close(w); }
  • 22. 22 wibble.h #ifndef WIBBLE_INCLUDED #define WIBBLE_INCLUDED ... module : header ... typedef struct wibble_tag wibble; struct wibble_api { wibble * (*open )(const char *); ... int (*close)(wibble *); }; extern const struct wibble_api wibbles; #endif
  • 23. 23 wibble.c #include "wibble.h" ... ... module : source static static linkage wibble * open(const char * name) { ... } ... static int close(wibble * stream) no need to write { ... &open, &close }; const struct wibble_api wibbles = { open, ..., close };
  • 24. 24 • opaque type memory management…  clients cannot create objects since they don't know how many bytes they occupy wibble.h ... typedef struct wibble wibble; ... #include "wibble.h" void client(void) { wibble * pointer; ...    wibble value; ADT ... ptr = malloc(sizeof(*ptr)); }
  • 25. 25 • an ADT can declare its size!  clients can now allocate the memory  true representation remains abstract  shadow data type wibble.h typedef struct wibble { unsigned char size[16]; } wibble; bool wopen(wibble *, const char *); void wclose(wibble *); #include "wibble.h" void client(const char * name) { wibble w; if (wopen(&w, name)) } ... wclose(&w); 
  • 26. 26 • implementation needs to…  define the true representation type wibble.c the analogy is that the #include "grommit.h" true type casts #include "flange.h" shadowed type a shadow which reveals only its size typedef struct { grommit g; flange f; ... } wibble_rep; wibble.h typedef struct wibble { unsigned char size[16];  } wibble; Still some problems though…
  • 27. 27 • the size of the type must not be smaller than the size of the type it shadows  assert only works at runtime  it would be safer to check at compile time wibble.h wibble.c typedef struct wibble typedef struct { { problem 1 ... ... } wibble; } wibble_rep; assert(sizeof(wibble) >= sizeof(wibble_rep)) 
  • 28. 28 • use a compile time assertion  you cannot declare an array with negative size compile_time_assert.h #define COMPILE_TIME_ASSERT(desc,exp) ¬ extern char desc [ (exp) ? 1 : -1 ]  #include "compile_time_assert.h" COMPILE_TIME_ASSERT(ok, 1 == 1); deep magic #include "compile_time_assert.h" COMPILE_TIME_ASSERT( your_message, 1 == 0);  gcc error: size of array 'your_message' is negative
  • 29. 29 wibble.c #include "wibble.h" #include "flange.h" #include "grommet.h" #include "compile_time_assert.h" compatible size typedef struct { grommet g; flange f; } wibble_rep; COMPILE_TIME_ASSERT( sizeof_wibble_not_less_than_sizeof_wibble_rep, sizeof(wibble) >= sizeof(wibble_rep)); ...  
  • 30. 30 • the two types must be alignment compatible  this means the first member of both types must be alignment compatible wibble.h typedef struct wibble { unsigned char size[16]; } wibble; problem 2 wibble.c typedef struct { grommit g;  flange f; ... } wibble_rep;
  • 31. 31 • use a union to force alignment alignment.h typedef union alignment solution { char c,*cp; int i,*ip; long l,*lp; long long ll,*llp; float f,*fp; double d,*dp; long double ld,*ldp; void *vp; void (*fv)(void); void (*fo)(); void (*fe)(int,...); } alignment; wibble.h List all the primitive types in here. #include "alignment.h" One must have the strictest alignment ... typedef union wibble { alignment universal; unsigned char size[16]; } wibble;  ...
  • 32. 32 • unions are much rarer than structs  design is as much about use as implementation forward declaration client.h typedef struct wibble wibble; ...  problem 3 Oooops: it's a union not a struct  6.7.2.3 Tags Paragraph 1, sentence 2 Where two declarators that use the same tag declare the same type, they shall both use the same choice of struct, union, or enum.
  • 33. 33 • put a union object inside a struct!  drop the union tag name wibble.h ... typedef struct wibble  { wrapper struct union { alignment universal; unsigned char size[16]; } shadow; one object } wibble; ...  6.7.2.3 Tags Paragraph 4, sentence 2 Each declaration of a structure, union, or enumerated type which does not include a tag declares a distinct type
  • 34. 34 • conversion can be via memcpy  helper function allows assignment wibble.c  wibble.c inline wibble shadow(wibble_rep * src) static { conversions 1 wibble dst; memcpy(&dst, src, sizeof(*src)); return dst; } bool wopen(wibble * w, const char * name) { wibble_rep rep = { .g = ..., .f = ..., }; *w = shadow(&rep); ...; }
  • 35. 35 • conversion can be via pointer casts  helper function allows  operator wibble.c  static inline wibble_rep * rep(wibble * w) conversions 2 { return (wibble_rep *)w; } void wclose(wibble * w); { rep(w)->g = ...; rep(w)->f = ...; ... }
  • 36. 36 • This course was written by Expertise: Agility, Process, OO, Patterns Training+Designing+Consulting+Mentoring { JSL } Jon Jagger jon@ jaggersoft.com Contact www.jaggersoft.com