简体   繁体   中英

C++ set default arguments with #define

Can I set default arguments to a #defined value?

#define WIDTH 1920
#define HEIGHT 1080

void calculate(int width = WIDTH, int height = HEIGHT) {
    //do stuff
}

You can use #define . But should you?

#define ignores scope, and has other problems . This code will work just as well, without making anyone gasp in horror at unnecessary defines.

enum {WIDTH  = 1920 };
enum {HEIGHT = 1080 };

void calculate(int width = WIDTH, int height = HEIGHT) 
{
  //do stuff
}

This will also work:

const int WIDTH  = 1920;
const int HEIGHT = 1080;

void calculate(int width = WIDTH, int height = HEIGHT) 
{
  //do stuff
}

As will this, though it's not as clear:

void calculate(int width = 1920, int height = 1080) 
{
  //do stuff
}

Yes. The WIDTH and HEIGHT macros will just expand to 1920 and 1080 . This will do the same as :

void calculate(int width = 1920, int height = 1080) { // ...

Depending on your case, you may prefer static const int over macros for different reasons, which you can find on this answer ; or at least rename WIDTH and HEIGHT to something more specific, because this seems very conflict-prone. As stated by the other answer, one advantage to using static variables is that they are scoped.

C++17 note : You will be able to inline a variable . If the compiler doesn't/can't do this already over consts during the optimisation stage, you may prefer this approach in the future.

Yes you can, but dont do it if you can avoid it. Imagine you have the defines in a header

// foo.h
#define WIDTH 123

and for some reason you include this header in some other header containing something like the following:

// bar.h
#include "foo.h"
int bar(int WIDTH) { return WIDTH*2; }

To my experience this can lead to very nasty bugs, that can be avoided completely if you simply dont use macros.

You might argue that the capitalization saves you from such mistakes, however then you still could have

// moo.h
#define WIDTH 321
#include "foo.h"

This wont even lead to a compiler error, but even harder to trace bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM