-2

What will the program print when the inputs are 2,3?

#include <stdio.h>
#define min(a,b)  ((a) > (b) ? (b) : (a))
#define inc(a)    a++
#define mult(a,b) (a * b)

int main(void) {
    int x = 1, y = 2;
    scanf("%d %d",&x,&y);
    printf("min(%d,inc(%d))",x,y);
    printf("=%d\n",min(x,inc(y)));
    printf("min(mult(%d,%d+2),11)",x,y);
    printf("=%d\n",min(mult(x,y+2),11));
    return 0;
}

edit: I get funny answer for negative numbers i.e -1,-2.
Why is inc(-2) change y to zero instead of -1?

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
maxflow
  • 869
  • 4
  • 10
  • 16
  • 2
    Have you tried running it to see what the output will be? – vmpstr Jun 06 '12 at 16:10
  • yet again, possible duplicate of [What's the side effect of the following macro in C ? Embedded C](http://stackoverflow.com/questions/7299286/whats-the-side-effect-of-the-following-macro-in-c-embedded-c) – Jens Gustedt Jun 06 '12 at 16:40
  • mult(x,y+2)=>x*y+2, #define mult(a,b) ((a)*(b)) – BLUEPIXY Jun 06 '12 at 23:13

3 Answers3

2

Think of a macro as simply string replacement. Just replace the macro name and parentheses with the body of the macro definition, replacing the macro parameters with what is passed in. An example is easier:

#define hello(a) a+a
...
int y = hello(x);

Would be replaced with:

int y = x+x;

To answer your question, do this manually, and very, very carefully. For nested macros, start with the inside one. Did I mention do this carefully? Don't add or remove any sets of parentheses.

Peter
  • 14,559
  • 35
  • 55
1

The output would be:

min(2,inc(3))=2
min(mult(2,4+2),11)=11

What do you mean with overwrite? If you define a function like you did above and call for example this:

inc(x);

.. then the compiler turns it into x++. The variable a is just a name for the "paramter" and will also be replaced by the real variable.

Stefan Fandler
  • 1,141
  • 7
  • 13
  • If I try negative numbers, say -1 and -2 I get a funny answer. min(-1, inc(-2)) where inc(-2) = -1 (since inc(a)=a++ hence -2+1=-1) The problem is when I run this program the y value is changed to ZERO not -1. it will print "min(mult(-1,0+2),11)". It is clear that inc(y)=inc(-2) will change y to zero and not -1. Why is this? – maxflow Jun 07 '12 at 02:24
0

What operating system are you running? you can easily run this yourself and see the results

if your on Windows I would suggest getting CodeBlocks or Visual Studios

if your on Linux or MAC , learn to compile from terminal using gcc or g++

pyCthon
  • 11,746
  • 20
  • 73
  • 135