Menu

Why won't this macro work?

2009-03-05
2012-09-26
  • Andrew Charbonneau

    include <stdio.h>

    define rectangle_A(x1,x2) (x1*x2)

    int main(void)
    {
    / Declare variables. /
    double side1, side2;

    /* Ask user for input. */
    printf(&quot;Enter the length of the first side and length of the second side: \n&quot;);
    scanf(&quot;%lf lf&quot;,&amp;side1,&amp;side2);
    
    /* Print result to screen. */
    printf(&quot;The area is: %f \n&quot;,rectangle_A(side1,side2));
    
    system (&quot;PAUSE&quot;);
    /* Exit program*/
    return 0;
    

    }

    I ALWAYS END UP GETTING 0?

     
    • cpns

      cpns - 2009-03-05

      It is not the macro. You have simply omitted the % from the second format specifier in the scanf call.

      Some advice:

      1) You could have avoided blaming the macro by testing the macro on its own with direct literal constant values.

      2) scanf is problematic, and best avoided if you want robust code. If you knew how to avoid the problems it may cause, you'd probably opt for something simpler. Check the FAQ's for scanf here: http://c-faq.com/stdio/index.html

      3) If you do use scanf, check its return value - it returns thw number of fields successfully converted, so you need it to return 2 in this case to be valid.

      4) In GCC (and therefore Dev-C++), you can add the following compiler options -Wformat -Werror, andwill trap format specifier mismatches (although I am not sure it will detect additional arguments as in this case). I'd recommend -Wall too for good measure and better quality code.

      5) Don't use macros, they are bad for a number of reasons. Most of the reasons arise from the fact that they are processed by the pre-processor not the compiler, and the pre-processor knows nothing about valid C code.

      6) If you ignore (5), at least use safe macro practices - you have fallen into the number one macro pitfall!

      define rectangle_A(x1,x2) ((x1)*(x2))

      you need the parentheses to ensure the expected evaluation order is the arguments passed are expressions involving operators and not simple values. Macros are just text substitutions, the expansion of a macro may not be valid C code, but you only find out when the compiler processes the expansion, but all you see is teh macro, not what the compiler sees, so often the errors are hard to figure.

      7) Use a debugger

      8) Use a good quality debugger

      9) Unfortunately (8) implies not using Dev-C++

      Clifford

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.