Question

FAILED macro

Macro (computer science)

After I read the articles above, I still not very sure whether macro is just a function or anything else. Is macro equal to function?

Example:

    //  Create a Direct3D 9 device.
    hr = direct3D9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dPP, &d3dDevice);

    //  Cout out the message to indicate the failure.
    if(FAILED(hr))
       return 0;
Was it helpful?

Solution

In C and C++ a macro is a "replace this with that" type mechanism, and not at all the same as a function in a lot of senses. It can SOMETIMES be used to replace a function, but you should be very careful. Some famous "failures" in macros used as functions are as follows:

#define SQR(x) x * x

.... 

int x = 5;
int s = SQR(x+1);

This will not give 36, but (x + 1 * x + 1), which in my head makes 12 - not what you wanted. Can be fixed with using a function, or by adding extra parenthesis around x in the SQR macro.

Another "clever" use of macro:

#define IS_UPPER(c)  ((c) >= 'A' && (c) <= 'Z')

char *str = "Some String With a few Upper Case letters";
int uppers = 0;
while(*str) if (IS_UPPER(*str++)) uppers++;

Now, this will go wrong (uppers is guaranteed to be zero in this particular case, if we avoid crashing due to "missing" the end marker and keep going on...), becasue:

IS_UPPER(*str++)

translates to:

(*str++) >= 'A' && (*str++) <= 'Z'

which, if str is at the start of the string "Some ...", will be true for the first step, but not true for the second step since we are now pointing at the 'o' which is not less or equal to 'Z'. Using a function would work "as expected" here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top