Trouble with Macros!?

This is a discussion on Trouble with Macros!? within the C Programming forums, part of the General Programming Boards category; Hey everyone, I'm new to this site, but wish I could have found it sooner! I'm taking an online programming ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    7

    Exclamation Trouble with Macros!?

    Hey everyone,
    I'm new to this site, but wish I could have found it sooner! I'm taking an online programming course and therefore have limited availability in contacting my instructor for questions about the assignments/text... and this assignment in particular is stumping me even after going through a few old tutorials.

    I have the code somewhat close to what it needs to be... I hope! But I can't remember, or maybe I never actually knew, how to let a user assign a value to the array and then enter their own array numbers.

    Also, I think I'm having a compatability problem with my compiler again with the #define line.....

    Suggestions/Help? Please

    Code:
    /* SUMARRAY Marco use */
    #include <stdio.h>
    #include <stdlib.h>
    #define SUMARRAY(a, num_elements) for (i=0; i < num_elements; i++) sum = sum + a[i]; sum;
    
    int main( void )
    {
    	int x;
    	int l;
    	int d;
    	int i;
    	int sum = 0;
    	int num_elements;
    
    	printf("Enter the number of numbers to be summed up to 20: \n");
    	scanf("%d", &num_elements);
    	
    	int a[20] = {};
    	
    	for (l=0; l<x; l++){
    		printf("Enter number you wish to sum, then press ENTER: \n");
    		scanf("%d", &d);
    	}
    
    	   
           sum = SUMARRAY(a[i], x); 
    
    		printf("The sum is %d\n", sum);
    
    		system ("PAUSE");
    		return 0;
    }
    I have a feeling some of this may be extranneous coding, but its the user definition that seems to be giving me trouble.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Without going into great details, try this:

    Code:
    SUMARRAY(a, num_elements);
    Note: the difference is that you're passing the array without the index, and you're not assigning it to sum (because the macro is already doing that).

    Another error is that you're using x, but you never initialized it. You might want to turn up the warning level on your compiler.

    Next time, try posting the error message, and anything else that could help us out. Also, your usage of a macro in this manner is not good. It relies on various variables being declared, and it hides the details of what is happening. IMO, you are better off keeping the contents of the macro in the code, or moving it off into a separate function.

    Welcome to Cboard, and I hope you do well with your course. Be industrious and motivated and you should do well in general with C.

  3. #3
    Registered User
    Join Date
    Jul 2008
    Posts
    7
    Thanks so much! That makes perfect sense, I think I'm correctly setting up the Marco now, but I'm getting an error when I try to pass the user generated values actually into the array. Do I need to use a modify function?

    Code:
    #define SUMARRAY(a, num_elements);
    
    int main( void )
    {
    	int num_elements;
    	int l;
    	int d;
    	int i;
    	int sum = 0;
        int a[20] = {};
    
    	printf("Enter the number of numbers to be summed up to 20: \n");
    	scanf("&#37;d", &num_elements);
    	
    	
    	for (l=0; l<num_elements; l++){
    		printf("Enter number you wish to sum, then press ENTER: \n");
    		scanf("%d", a[num_elements]);
    		
    	}
    
           SUMARRAY(a[i], num_elements)
    		   for (i=0; i < num_elements; i++){
    			   sum += a[i];
    		   }
    The program will open and run to the first loop of the first for loop then it crashes. I know I'm passing this value incorrectly...I also tried
    Code:
    	for (l=0; l<num_elements; l++){
    		printf("Enter number you wish to sum, then press ENTER: \n");
    		scanf("%d", d);
                                    a[num_elements] = d;
                                    }
    It gave me the same error and also tells me after the program opens ( in a Windows' pop-up that the variable d is uninitialized). But, I clearly initiailized it at the beginning of main using int d;

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Code:
    scanf("%d", d);
    You have a working scanf earlier in your code. Compare and contrast.

    Code:
    scanf("%d", a[num_elements]);
    Compare and contrast, AND ask yourself this: do you want to write each number in the same slot in your array? No? Then maybe you should use a moving variable, rather than one that's standing still.

  5. #5
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by equss89 View Post
    Code:
    #define SUMARRAY(a, num_elements);
    Now your macro does absolutely nothing.

  6. #6
    The larch
    Join Date
    May 2006
    Posts
    3,573
    There should be a compiler option to output code after preprocessing.

    Macro's are find and replace instructions. Your original attempt to use the macro expands to this:

    Code:
    /*sum = SUMARRAY(a[i], x); =>*/
    sum = for (i=0; i < x; i++) sum = sum + a[i][i]; sum;;
    This doesn't look like valid and meaningful C code?

    In any case the macro seems exceptionally poor. For one thing it relies on variables i and sum being declared by the user.

    I don't see why you wouldn't turn SumArray into a function instead, in which case you could use it similarly to how you attempted:
    Code:
    int SumArray(int array[], int max);
    
    ...
    sum = SumArray(a, num_elements);
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  7. #7
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Not vary familiar with macros, but this should work (i hope):
    Code:
    #define SUMARRAY(a, num_elements, sum)   for(i=0; i<num_elements; ++i) sum+=a[i];
    of maybe this is better:

    Code:
    #define SUMARRAY(a, num_elements, sum)  sum=0; for(i=0; i<num_elements; ++i) sum+=a[i];
    or using C99, so you don't need to depend of i being declared elsewere:
    Code:
    #define SUMARRAY(a, num_elements, sum)   sum=0; for(int i=0; i<num_elements; ++i) sum+=a[i];

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    And so that it works OK if you put have something like this:
    Code:
        if(x) SUMMARY(a, num_elements, sum);
    you should wrap your code with do ... while(0), like this:
    Code:
    #define SUMARRAY(a, num_elements, sum)   do { sum=0; for(int i=0; i<num_elements; ++i) sum+=a[i]; } while(0)
    Also, note, no semicolon at the end, since it's customary to add one at the end of the macro invocation - and sometimes things get confused when you have two semicolons in a row, so better not to have one inside the macro.

    I do, still, prefer to have a function. It is highly likely that the function will be inlined if it's that small, so performance is not a reason for having a macro. And I can't really think of any other purpose for using a macro in this particular case.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,252
    Quote Originally Posted by anon View Post
    There should be a compiler option to output code after preprocessing.
    Some compilers support that.

    For example, gcc has the -E command line option, which stops after preprocessing and sends the output of the preprocessor to standard output device.

    Some other compilers come bundled with the preprocessor as a separate program.

    In terms of the original problem, the do .... while (0) approach described by matsp is common practice when using macros to execute multiple statements.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by grumpy View Post
    Some compilers support that.

    For example, gcc has the -E command line option, which stops after preprocessing and sends the output of the preprocessor to standard output device.

    Some other compilers come bundled with the preprocessor as a separate program.

    In terms of the original problem, the do .... while (0) approach described by matsp is common practice when using macros to execute multiple statements.
    And I believe both TC and CL supports -E or /E for the same purpose.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    What I had posted was to change the invokation of the macro, not the macro definition itself.

  12. #12
    Registered User
    Join Date
    Jul 2008
    Posts
    7
    Oh goodness -- Thank you MacGyver. I rewrote things again and this definietly helped! Everyhting runs, but I'm now having trouble using a moving element in the scanf to allow the numbers to be stored in the array in different positions instead of over-writing the number that the user just entered...
    Code:
    	printf("Enter the number of numbers to be summed up to 20: \n");
    	scanf("%d", &num_elements);
    	
    	int a[20] = {};
    	
    	for (l=0; l<num_elements; l++){
    		printf("Enter number you wish to sum, then press ENTER: \n");
    		scanf("%d", a);
    	}
    The text I'm using makes no references to storing numbers in array in this manner, only strings of text. =[
    When the sum MACRO runs, it returns the value of the last number entered, not the actual sum.
    Last edited by equss89; 07-18-2008 at 02:19 PM.

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Think about where you want the user's typed number to go. Hint: The answer "a" you have in your code is not specific enough.

  14. #14
    Registered User
    Join Date
    Jul 2008
    Posts
    7

    Thumbs up Thank You!

    Think about where you want the user's typed number to go. Hint: The answer "a" you have in your code is not specific enough.
    Although this was a open ended hint, it was perfect! Thanks for pointing me in the right direction without doing it for me.

    I managed to fix the program by rewriting that line as
    Code:
    	for (l=0; l<num_elements; l++){
    		printf("Enter number you wish to sum, then press ENTER: \n");
    		scanf("%d", &a[l]);
    	}
    and the program now reads:
    Code:
    /* SUMARRAY Marco use */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define SUMARRAY(a, num_elements) for (i=0; i < num_elements; i++) sum = sum + a[i]; sum;
    
    int main( void )
    {
    	int l;
    	int i;
    	int sum = 0;
    	int num_elements;
    
    
    	printf("Enter the number of numbers to be summed up to 20: \n");
    	scanf("%d", &num_elements);
    	
    	int a[20] = {};
    
    	for (l=0; l<num_elements; l++){
    		printf("Enter number you wish to sum, then press ENTER: \n");
    		scanf("%d", &a[l]);
    	}
    
    		SUMARRAY(a, num_elements); 
    
    		printf("The sum is %d\n", sum);
    
    		system ("PAUSE");
    		return 0;
    }
    Thanks again, everyone

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    #define SUMARRAY(a, num_elements) for (i=0; i < num_elements; i++) sum = sum + a[i]; sum;
    Whilst not illegal, it does absolutely nothing useful (unless sum is a hardware register that has some effect when being read).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Order of execution of preprocessor macros
    By DL1 in forum C Programming
    Replies: 2
    Last Post: 04-02-2009, 06:52 PM
  2. parameterized macros vs. functions
    By Tbrez in forum C Programming
    Replies: 3
    Last Post: 04-02-2009, 12:33 PM
  3. Macros inside of macros
    By Chewie8 in forum C Programming
    Replies: 2
    Last Post: 02-24-2008, 02:51 AM
  4. Replies: 6
    Last Post: 01-03-2007, 02:02 PM
  5. trouble scanning in... and link listing
    By panfilero in forum C Programming
    Replies: 14
    Last Post: 11-21-2005, 11:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21