Easy Tutorial
❮ Windows10 Mysql Installer Verilog2 Tf Sub ❯

Correct Writing of Macros and Macro Definition of Ternary Operators

Category Programming Techniques

Abstract: Macros are divided into two categories:

// Correct understanding of macros (macro definition of ternary operators)

// (1) Novice's way
#define MIN(A,B) A < B ? A : B

int a = MIN(1,2);
// => int a = 1 < 2 ? 1 : 2;
printf("%d",a);
// => 1

// Problem

int a = 2 * MIN(3, 4);
// => int a = 2 * 3 < 4 ? 3 : 4;
// => int a = 6 < 4 ? 3 : 4;
// => int a = 4;

// (2) Coder's way
#define MIN(A,B) (A < B ? A : B)

// Perfectly solved
 int a = 2 * MIN(3, 4);

// Problem
int a = MIN(3, 4 < 5 ? 4 : 5);
// => int a = (3 < 4 < 5 ? 4 : 5 ? 3 : 4 < 5 ? 4 : 5);  // Hope you still remember the operator precedence
//  => int a = ((3 < (4 < 5 ? 4 : 5) ? 3 : 4) < 5 ? 4 : 5);  // To make it less confusing for you, I've added parentheses to this expression
//   => int a = ((3 < 4 ? 3 : 4) < 5 ? 4 : 5)
//    => int a = (3 < 5 ? 4 : 5)
//     => int a = 4

// (3) Engineer's way
#define MIN(A,B) ((A) < (B) ? (A) : (B))

// Perfectly solved
int a = MIN(3, 4 < 5 ? 4 : 5);

// Problem
float a = 1.0f;
float b = MIN(a++, 1.5f);
// => float b = ((a++) < (1.5f) ? (a++) : (1.5f))

// (4) Expert's way
#define MIN(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; })

>

Source: https://my.oschina.net/iOScoderZhao/blog/916074

❮ Windows10 Mysql Installer Verilog2 Tf Sub ❯