Thread: Define a macro to sum the elements of an array

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    6

    Define a macro to sum the elements of an array

    So I think my professor's starting to run out of ideas for exercises, unless the real exercise here is to learn how weird macros are. He wants us to write one that sums the elements of an array, which I would think is a job for a function! I basically defined the macro as I would a function. I didn't think it was possible to return a specific variable though, so I added a printf() on the end.

    I hope someone can bear with me here. I would much rather use a function, but I wouldn't get credit for the assignment if I did! Ugh. Well, here's what I have:

    Code:
    /*Define and use a macro SUMARRAY to sum the values of a numeric array.*/
    
    #include<stdio.h>
    
    #define SUMARRAY( array[10] )                        \
    (                                                    \
       int total = 0;                                    \
       int arraySize = sizeof(array[10]) / sizeof(int);  \
       while ( i <= arraySize)                           \
       {                                                 \
          total += array[i];                             \
          i++;                                           \
       }                                                 \
       printf ( "%d", total );                           \
    )                                                    \                            
    
    int main()
    {
        int sum = 0;
        int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        
        SUMARRAY( array[10] );
        
        return 0;
        
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Your compiler should be giving you some feedback. What are the error messages and what do you understand of them?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jul 2011
    Posts
    6
    Quote Originally Posted by laserlight View Post
    Your compiler should be giving you some feedback. What are the error messages and what do you understand of them?
    Sorry for not including the error message to begin with.

    Line 22 `SUMARRAY' undeclared (first use this function)
    It seems to me that it isn't recognizing my definition. I'm still trying to follow the #define identifier replacement-code format by using parentheses in the right places. I thought maybe it had something to do with me using "array[10]" for both the parameter and argument, yet I still get the same error when I change the macro's parameter (and it's appearances in the body of the macro) to arr[10]. I'm not sure I can think of anything else that might make it unidentifiable.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The error message is surprising vague. Anyway, for starters, the macro parameter should be a name only. The [10] does not belong there. Within the macro, you should be using the array name when you want to refer to the array. array[10] is actually an element of the array (that does not exist).

    Also, be careful of the difference between braces and parentheses, and you should not have any characters after the \ that ends each physical line.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I assume you only want to use array[10] because you use sizeof, but that's not what sizeof would operate on. If I declare

    int array[10];

    The name of the thing is array.
    That's what I see.

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by laserlight View Post
    Your compiler should be giving you some feedback.
    You have a talent for understatement, laserlight

    In terms of specifics for the OP (which I have picked up only on a quick look)

    1) Take the array dimension out of the argument list of the macro definition. That will probably cause the preprocessor to reject the definition, and explain why subsequent attempts to use the macro give a compile error referring to the name of the macro.

    2) The body (expansion) of the macro should not be delimited by brackets (). Use curly braces instead.

    3) If you want the size of the array, compute sizeof(array) not sizeof(array[10]). sizeof(array[10]) gives the size of an element of the array, not the size of thw whole array. Since array is an array of int, computing sizeof(array[10])/sizeof(int) will always give a value of 1.

    4) If you are going to report error messages in a forum, don't only report the last error message you see. The compiler (or, more specifically, the preprocessor) will report an error at the macro definition before it will emit the error message you reported. By being selective, you have omitted information that is directly relevant to your problem. Incidentally, if you had taken time to interpret ALL the error messages, you could have puzzled out a solution to your problem for yourself.

    5) Your macro needs to define the variable i and initialise it to zero, otherwise it will trigger other error messages (assuming you fix problems pointed out above) from the compiler.

    6) Your macro is attempting to loop over array elements to a maximum index value of arraySize. Array indices run from 0 to size-1, not from some random value to size.

    7) Bear in mind that your code will not work for pointers. That means if you pass the array to a function, the macro will not work in the body of that function.

    8) Your would be better off writing a function to do what you want, rather than a macro. If for no other reason that avoiding the silliness you have introduced in your macro - do such silliness in a function rather than in a (broken) macro, and the compiler will emit meaningful error messages.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by volte View Post
    /*Define and use a macro SUMARRAY to sum the values of a numeric array.*/
    Code:
    int sum( int array[], size_t nelm )
    {
        int s = 0;
        size_t x = 0;
        for( x = 0; x < nelm; x++ )
            s += array[ x ];
        return s;
    }
    /* and now the magic */
    #define SUMARRAY sum
    Or you could make it an actual macro, but you will need to pass the value to store the sum in, initialized to zero:
    Code:
    #define SUMARRAY(a,b,c)do(c)+=(a)[(int)--(b)];while((b))
    Hm...that looks about right.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How overload a define macro?
    By 6tr6tr in forum C++ Programming
    Replies: 19
    Last Post: 04-24-2008, 03:52 PM
  2. Is it possible to set type for define macro?
    By 6tr6tr in forum C++ Programming
    Replies: 5
    Last Post: 04-16-2008, 01:32 PM
  3. Newbie question about the define macro
    By lawina in forum C++ Programming
    Replies: 11
    Last Post: 05-18-2006, 06:47 PM
  4. Tricky #define macro...
    By willkoh in forum Windows Programming
    Replies: 4
    Last Post: 04-06-2005, 12:09 PM
  5. macro (#define) question
    By Darrok in forum C++ Programming
    Replies: 30
    Last Post: 12-20-2001, 05:01 PM