tags:

views:

115

answers:

5
+2  Q: 

#define file type

Is

#define LBitmap std::list < CBITMAP *>

a good practice?

Edit: Alright, what can I do to convince my boss that this is bad practice?

+8  A: 

No, the use of preprocessor macros (#define) is discouraged in C++. Use a typedef instead:

typedef std::list<CBITMAP *> LBitmap;

Edit: to convince your boss, you can use the pointer trick Pardeep posted, but it's even more fun instructive to introduce a subtle bug using references:

#define FooRef Foo &

struct Bar {
    Foo a, b;
};

void func(Bar &bar)
{
    FooRef a = bar.a, b = bar.b;
    a = some_value;
    b = another_value;
}
larsmans
+12  A: 

No, its not a good practice to use #define in C++.

Its good to use typedef as this has a well defined scope

typedef is scope defined and compiler interprets its definition each time it meet which is not the in case of #define. #define is interpreted as compile time itself.

Here is the MSDN definition of typedef and #define

A typedef declaration introduces a name that, within its scope, becomes a synonym for the type given by the type-declaration portion of the declaration

When using DEFINE statements, all instances of that statement are replaced by the value of the statement during a preprocessing phase.

#define LBitmap std::list < CBITMAP *>   // BAD

typedef std::list < CBITMAP *> LBitmap  // GOOD

To convince your Boss

#define CHARPTR char*

CHARPTR a, b;

After preprocessing, that line expands to

char* a, b;

Here, only variable a is of type char * whereas b is simply char

If you use typedef

typedef char* CHARPTR;
CHARPTR a, b;

Here both a and b are both of type char *

Pardeep
@Pradeep shouldnt typedef syntax be the otherway round :) typedef std::list<CBITMAP *> LBitmap;
Als
@Als Thanks Als, it was mistake when quoting example. Corrected this in solution
Pardeep
+1  A: 

No. Its better to use a typedef in this case as:

typedef std::list<CBITMAP*> LBitmap;
codaddict
+2  A: 

No, for defining type aliases, there is a much better facility:

typedef std::list< CBITMAP *> LBitmap;

A #define results in a textual replacement, which can lead to surprising results. typedef on the other hand creates a proper alias for some other type.

Bart van Ingen Schenau
+3  A: 

#define is just an textual replace and it can lead a few problems, resulting in code that you dont intend to have.
typedef if the right way to give alias names for datatypes etc.

Heres an example where #define fails horribly!

#define CHARPTR_DEFINE char*  
typedef char* CHARPTR_TYPEDEF;
CHARPTR_DEFINE ptr1, ptr2;   --> evaluates to char *ptr1, ptr2;
CHARPTR_TYPEDEF ptr3, ptr4;  -->evaluates to char *ptr3,*ptr4;
Als