Home > Blockchain >  Converting C to Java understanding macro's in C
Converting C to Java understanding macro's in C

Time:02-06

I'm told the following C code

#define ADD(a, b) a   b

// example function
void foo()
{
  int i = ADD(1, 2); // add two ints
  double d = //doubles
    ADD(3.4, 5.6);

  int sly = ADD(1, 2) * 3; // not what it appears to be
}

converts to this Java code

package demo;

public class DemoTranslation {
    public static int add(int a, int b) {
        return a   b;
    }

    public static double add(double a, double b) {
        return a   b;
    }

    /**
     * example function
     */
    public static void foo() {
        int i = add(1, 2); // add two ints
        double d = /* doubles */ add(3.4, 5.6);

        int sly = 1   2 * 3; // not what it appears to be
    }
}

1 2*3 in java = 7. How does the C code produce that and not 9?

CodePudding user response:

C macro replacement operates on lexical tokens, at a lower level than semantic analysis of the program.

Given #define ADD(a, b) a b, the source text ADD(1, 2) * 3 is replaced by 1 2 * 3, which is evaluated as 1 (2•3) = 7.

Macro replacement was created for convenience in early primitive programming environments. As such, some of the motivation for developing it was simply typing convenience (editing source files could be a burdensome task in hardware of the era), and additional uses of it grew, including using macros to represent simple expressions. To deal with the fact that macros perform lexical substitution rather than semantic functions, C programmers have learned to parenthesize arguments in macro replacement lists as well as the entire list when macros are being used for expressions. So a C programmer would define ADD as:

#define ADD(a, b) ((a)   (b))

Then ADD(1, 2) * 3 will be replaced by ((1) (2)) * 3, which will be evaluated as (1 2)•3 = 9.

  • Related