top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

PreProcessor issue in C/C++? Why is the answer 7?

+3 votes
328 views
#include<stdio.h>
#include<conio.h>
#define PROD(x) (x*x)
void main()
{
 clrscr();
 int p=3,k;
 k=PROD(p+1); //here i think value 3+1=4 would be passed to macro
 printf("\n%d",k);
 getch();
}

In my opinion, the output should be 16, but I get 7. Can anyone please help me why?

posted Apr 21, 2014 by Muskan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+3 votes
 
Best answer

Preprocessor commands are hard replacement before the compilation hence after the replacement your statement will look like this

Before Replacement

k=PROD(p+1); 

After Replacement

k=(p+1*p+1); // which is 3+1*3+1 = 7 

To correct the behavior please change the #define PROD(x) (x*x) to #define PROD(x) ((x)*(x)) by inserting the () around the variable will do the trick.

answer Apr 22, 2014 by Salil Agrawal
Similar Questions
+1 vote
int main()
{
    int *x;
    int *y;
    x * y;
    x - y;
    x + y;
}

In the above program we see the error at x*y and x+y not on the x-y. Please explain?

+5 votes
#include<stdio.h>
#include<string.h>
main()
{
    char p[100];
    int i,len;
    printf("Enter a string\n");
    scanf("%[^\n]",p);
    len=strlen(p);
    for(i=0;i<len-1;i++)
    {
        if(a[i]==a[i+1])
              p[i]=p[i+1];
    }
    printf("String :  %s\n",p);
}
+4 votes
#include<stdio.h>
int var;
int var;
int var;

int main(void) { 
  printf("%d \n",var); 
  return 0;
}
...