Results 1 to 2 of 2

Thread: Is macros necessary in C++?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2001
    Posts
    396

    Question Is macros necessary in C++?

    My question here is "Is macros a more of the C thingy? Is the use of macros encouraged in C++ where the same thing can be done in plain code?" Here's I am not talking about the use of macros in preprocessor headers but macros in source code.

    Here 's an extract from MSDN

    Code:
    #include <stdio.h>
    #define EPSILON 0.0001   // Define your own tolerance
    #define FLOAT_EQ(x,v) (((v - EPSILON) < x) && (x <( v + EPSILON)))
    void main()
    {
        float a,b,c
        a=1.345f;
        b=1.123f;
        c=a+b;
       //if (FLOAT_EQ(c, 2.468))        // Remove comment for correct result
       if (c == 2.468)                 //Comment this line for correct result
       printf("They are equal\n");
    else
       printf("They are not equal!!The value of c is %13.10f,or %f",c,c);
    }
    I can understand the above code very well. There were some macros that I was browsing some time ago, that I cannot understand fully. However I understand the logic of the source and macros(what they are trying to do.).

    If I were to implement that source myself, I will turn that macros into my plain code as I still do not understand fully how macros worked.

    However the main question is "Is macros necessary and encouraged in C++?"

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    No, not particularly.

    Both of those could be implemented differently:
    Code:
    #include <stdio.h>
    const double EPSILON = 0.0001;   // Define your own tolerance
    inline bool FLOAT_EQ(double x, double v) {
        return (((v - EPSILON) < x) && (x <( v + EPSILON)));
    }
    
    void main()
    {
        float a,b,c
        a=1.345f;
        b=1.123f;
        c=a+b;
       //if (FLOAT_EQ(c, 2.468))        // Remove comment for correct result
       if (c == 2.468)                 //Comment this line for correct result
       printf("They are equal\n");
    else
       printf("They are not equal!!The value of c is %13.10f,or %f",c,c);
    }
    Macros are almost unnecessary now with templates and inline functions - the preprocessor should only really be used for conditionally including blocks of code.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width