whats is OOP up-arrow binary Arduino hints and tips - Using typedefs - 1
Dual arduinos in control panel hdr

Using typedefs - what are they anyway?


A typedef is a C/C++ language construct allowing the programmer to specify extra type names for variables, parameters, or values.

Examples of typedef declaration and usage

    // a 16 bit, signed value
    typedef short int16_t; 
    
    // a 32 bit unsigned value suitable for use with micros() or millis()
    typedef unsigned long bcsjTime;
    
    
    int16_t  data1;  // declare variable data1 to be a 16 bit, signed integer
    
    bcsjTime duration;  // declare a 32 bit unsigned integer for use with micros()
    
    int checkTime( bcsjTime t );  // prototype of function accepting an unsigned long parameter
    
    

Why should I used a typedef instead of using the original type?

That's a good question. I was asked about the bcsjTime type (declared in bcsjTimer.h).

Certainly the

   bcsjTimer::start( bcsjTime duration )

function could be written instead as

   bcsjTimer::start( unsigned long duration )

and be functionally the same. However, it's important that all time values be unsigned values. By using the bcsjTime typedef we can be sure that when we're handling a time value, we're doing so as unsigned 32 bit values.

Another reason is that when I see bcsjTime used to declare a variable or function parameter I know that element is intended to hold a time value instead of something else.