Using the % operator with preprocessor constants

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • zahy[dot]bnaya[At]gmail[dot]com

    #1

    Using the % operator with preprocessor constants

    hello,
    I have a constant declared as

    #define TABLESIZE 16*15*14*13*12* 11*10*9/3 /// 172972800

    I tried the following code:

    if (TABLESIZE == 172972800)
    {
    printf("%d\n",5 18763960%172972 800);
    printf("%d\n",5 18763960%TABLES IZE);
    printf("%d\n",T ABLESIZE);
    }



    My output is:

    172818360
    86486400
    172972800



    How can it be?
    Thanks

  • Victor Bazarov

    #2
    Re: Using the % operator with preprocessor constants

    zahy[dot]bnaya[At]gmail[dot]com wrote:[color=blue]
    > hello,
    > I have a constant declared as
    >
    > #define TABLESIZE 16*15*14*13*12* 11*10*9/3 /// 172972800[/color]

    It's not a constant. It's a piece of text. If you need a constant, use

    const long TABLESIZE = ....
    [color=blue]
    > I tried the following code:
    >
    > if (TABLESIZE == 172972800)
    > {
    > printf("%d\n",5 18763960%172972 800);
    > printf("%d\n",5 18763960%TABLES IZE);[/color]

    Substitute the contents of your 'TABLESIZE' macro here. What do you get?
    Write it down. Look what the '%' applies to.
    [color=blue]
    > printf("%d\n",T ABLESIZE);
    > }
    >
    >
    >
    > My output is:
    >
    > 172818360
    > 86486400
    > 172972800
    >
    >
    >
    > How can it be?[/color]

    Do NOT use macros when you need a constant.

    V
    --
    Please remove capital As from my address when replying by mail

    Comment

    • Ben Pope

      #3
      Re: Using the % operator with preprocessor constants

      zahy[dot]bnaya[At]gmail[dot]com wrote:[color=blue]
      > hello,
      > I have a constant declared as
      >
      > #define TABLESIZE 16*15*14*13*12* 11*10*9/3 /// 172972800
      >
      > I tried the following code:
      >
      > if (TABLESIZE == 172972800)
      > {
      > printf("%d\n",5 18763960%172972 800);
      > printf("%d\n",5 18763960%TABLES IZE);
      > printf("%d\n",T ABLESIZE);
      > }
      >
      >
      >
      > My output is:
      >
      > 172818360
      > 86486400
      > 172972800
      >
      >
      >
      > How can it be?[/color]

      Macros are evil.

      Rule 1* is to always put it in brackets:
      #define TABLESIZE (16*15*14*13*12 *11*10*9/3)

      Macros are text replacement so your second printf expands to:

      printf("%d\n",5 18763960%16*15* 14*13*12*11*10* 9/3);

      Rule one comes after at least 3 other rules, which essentially all say:
      Don't use macros!

      Ben Pope
      --
      I'm not just a number. To many, I'm known as a string...

      Comment

      Working...