Please Explain This C Code Snippet Mult(X, Y)X*Y?
#include <stdio.h>
#define mult(x,y)x*y  /* what does this mean ?? */

int main() 
{
  int a,b,answer;
  b=5;
  a=5;

  answer=mult(a+b,a+b);
  printf("%d",answer);

  return 0;
}

I'm using compiler gcc-4.9.2

1

1 Answer

If I understand correctly you want to know what #define mult(x,y) x*y does.

This a definition of a macro, during the compilation the compiler will replace, everywhere in the code, mult(x, y) by x*y.

In your code: answer=mult(a+b,a+b);

Will be replaced by: answer=a+b*a+b;

Whence the answer will be 35.

A correct way to use macros and to ensure they work properly is to include parentheses where they might be needed.

Therefore your define would be: #define mult(x, y) ((x)*(y)) to ensure the result is what you would expect 100

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest