ICanFathom ICanFathom - 2 months ago 8
C++ Question

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
}

Answer

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
}