Is it possible to use a if statement inside #define?

前端 未结 8 1867
名媛妹妹
名媛妹妹 2021-02-02 13:34

I\'m trying to make a macro with the following formula: (a^2/(a+b))*b, and I want to make sure that the there will be no dividing by zero.

#define          


        
8条回答
  •  眼角桃花
    2021-02-02 13:55

    I use macros with conditions quite a bit and they do have a legit use.

    I have a few structures that are essentially blobs and everything is just a uint8_t stream.

    To make internal structures more readable I have conditional macros.

    Example...

    #define MAX_NODES 10
    #define _CVAL16(x)(((x) <= 127) ? (x) : ((((x) & 127) | 0x80) ), ((x) >> 7))  // 1 or 2 bytes emitted <= 127 = 1 otherwise 2
    

    Now to use the macro inside an array ...

    uint8_t arr_cvals[] = { _CVAL16(MAX_NODES), _CVAL16(345) };
    

    Three bytes are emitted in the array, 1st macro emits 1 and the second 2 bytes. This is evaluated at compile time and just makes the code more readable.

    I also have... for example...

    #define _VAL16(x) ((x) & 255), (((x) >> 8) & 255)
    

    For the original problem... maybe the person wants to use the results with constants, but once again really comes down to where and how it's to be used.

    #define SUM_A(x, y) (!(x) || !(y)) ? 0 : ((x) * (x) / ((x) + (y)) * (y))
    float arr_f[] = { SUM_A(0.5f, 0.55f), SUM_A(0.0f, -1.0f), SUM_A(1.0f, 0.0f) };
    

    At runtime can have...

    float x;
    float y;
    
    float res = SUM_A(x,y); // note ; on the end
    

    I have a program that creates fonts that are included as code inside C programs and most values are wrapped around macros that split 32 bit values into 4 bytes, float into 4 bytes, etc.

提交回复
热议问题