Sven
Sven

Reputation: 2889

#define file type

Is

#define LBitmap std::list < CBITMAP *>

a good practice?

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

Upvotes: 3

Views: 575

Answers (5)

Fred Foo
Fred Foo

Reputation: 363797

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;
}

Upvotes: 9

Pardeep
Pardeep

Reputation: 949

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 *

Upvotes: 13

Alok Save
Alok Save

Reputation: 206616

#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;

Upvotes: 3

Bart van Ingen Schenau
Bart van Ingen Schenau

Reputation: 15768

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.

Upvotes: 2

codaddict
codaddict

Reputation: 455360

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

typedef std::list<CBITMAP*> LBitmap;

Upvotes: 1

Related Questions