Вот алгоритм pgras в Java:
public double ColourDistance(Color c1, Color c2)
{
double rmean = ( c1.getRed() + c2.getRed() )/2;
int r = c1.getRed() - c2.getRed();
int g = c1.getGreen() - c2.getGreen();
int b = c1.getBlue() - c2.getBlue();
double weightR = 2 + rmean/256;
double weightG = 4.0;
double weightB = 2 + (255-rmean)/256;
return Math.sqrt(weightR*r*r + weightG*g*g + weightB*b*b);
}
Ok, here. No runtime cost.
#define CLAIM(n) struct busy##n {}
CLAIM(58);
CLAIM(58);
If run twice it will error out:
z.c:4: error: redefinition of ‘struct busy58’
To extend the check to multiple compilation units you will want to wrap the macro in #if DEBUG
because we would be using the linker to detect the clash and hence would have a runtime footprint.
#define CLAIM(n) char busy##n = 1;
#define CLAIM(n) void busy##n() {} // bdonlan
Если вы можете себе позволить накладные расходы времени выполнения или если это просто для отладки, я бы просто создал что-то вроде функции IOPinOpen ()
, которая отслеживала используемые контакты вместо того, чтобы иметь дело с макро-обманом.
С другой стороны, обновленный ответ Марка Рэнсома стоил +1.
#define CLAIM_PIN(n) char claimed_pin_##n;
Now when two pieces of code try to claim a pin, the symbol will be doubly defined and either the compiler or the linker will generate an error.
Edit: Based on comments, this might turn out better:
#define CLAIM_PIN(n) void claimed_pin_#nn(void) {}