Thread: counting the number of #defines

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    347

    counting the number of #defines

    I have a number of #defines as of now it is around 50. I have to create an array of these number of #defines. In future the number of defines may increase so the array. Is it possible to count the number of defines in the program instead of manually counting and give it to the array. Please advise.
    Code:
    ex1:
    #define TEST1   0x11u
    #define TEST2   0x21u
    #define MAXSIZE  (0x02u)
    uint8_t array[MAXSIZE];
    
    ex2:
    #define TEST1   0x10u
    #define TEST2   0x15u
    #define TEST3   0x32u
    
    #define MAXSIZE  (0x03u)
    uint8_t array[MAXSIZE];
    Last edited by Satya; 03-24-2018 at 11:49 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    If you could use an enum instead of #defines, life is simpler.

    Or you can indirectly count the #defines so long as you're prepared to put them in an array.

    Or you use an external program to count them, and make a #define on the command line.
    Code:
    #include<stdio.h>
    
    #define TEST1   0x10u
    #define TEST2   0x15u
    #define TEST3   0x32u
    
    // place all the defines you want to count in here
    int dummy[] = {
      TEST1,
      TEST2,
      TEST3
    };
    
    enum {
      T1,
      T2,
      T3,
      TMAX,
    };
    
    
    char array[sizeof(dummy)/sizeof(*dummy)];
    char arr2[TMAX];
    char arr3[TEST_MAX];  // comes from -D on the command line
    
    
    int main(void)
    {
      printf("%zd\n", sizeof(array));
      printf("%zd\n", sizeof(arr2));
      printf("%zd\n", sizeof(arr3));
      return 0;
    }
    
    // Must be compiled with
    gcc -DTEST_MAX=$(egrep -c '#define TEST' foo.c) foo.c
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Counting number of occurence of digits in a number
    By Azeem in forum C Programming
    Replies: 16
    Last Post: 10-12-2012, 11:46 PM
  2. Counting the number of inegers in a number
    By jburn09 in forum C Programming
    Replies: 8
    Last Post: 09-19-2012, 12:52 PM
  3. Replies: 7
    Last Post: 12-04-2011, 10:43 PM
  4. Help with number counting program
    By Turtal in forum C Programming
    Replies: 11
    Last Post: 04-25-2009, 02:40 PM
  5. Counting Numbers in Array, not counting last number!
    By metaljester in forum C++ Programming
    Replies: 11
    Last Post: 10-18-2006, 11:25 AM

Tags for this Thread