Can someone explain me this code | SoloLearn: Learn to code for FREE!

0

Can someone explain me this code

What is the output of this code? #define prod(i, j) i * j int main() { int x = 3, y = 4; printf("%d", prod(x + 2, y - 1)); return 0; }

1/21/2021 4:49:05 PM

Cлaвeн Ђервида

7 Answers

New Answer

+3

Macros in C simply replace text. That's all they do. So if we call the macro defined in your code like this prod(2, 3) It will simply be replaced by 2*3 in the main code. In the same way, if call the macro like this prod(2 + 3, 4 - 2) It will simply be changed to '2 + 3 * 4 - 2'. So now, according to operator precedence '2 + 3 * 4 - 2' is 12, when actually (2+3) * (4-2) is 10. Same way in your code, printf("%d", prod(x + 2, y - 1)); will be changed to printf("%d", x + 2 * y - 1); Now according to operator precdence x + 2 * y - 1 = 3 + 2 * 4 - 1 = 3 + 8 - 1 = 10 So 10 is printed

+1

Yes. C/C++ macros basically replace text in your program. But using paranthesis around expressions passed as macro arguments can fix this problem atleast. For example printf("%d", prod( (x + 2), (y - 1))); here, prod( (x + 2), (y - 1) ) will change to (x + 2) * (y - 1) = (3 + 2) * (4 - 1) = 5 * 3 = 15

0

Is that only way for using macros?

0

Stupid question, but how can I say marcos in other word. What is the synonymous? 😅

0

I don't know any synonym of macro. But what is the problem in using 'macro'? I mean, why do you want a synonym of it?

0

Because i'm always think about the macros in Microsoft access and I'm not sure that is the same thing. That's why.

0

Cлaвeн Ђервида I haven't worked with Microsoft access/excel macros much but as far as I know, they record whatever operations you're doing and when they are called they repeat the operations. So I think it makes sense to say that they are just like macros in programming languages. Same as macros in microsoft access/excel, you can list a few statements in a C macro which you want to execute when the macro is called. For example, the following macro takes 4 arguments and constructs a single statement for loop that loops from start till end #define frange(start, stop, step, operation) for (int _ = start; _ < stop; _ += step) operation when you call frange in your code, it will become a for loop int sum = 0; frange(0, 10, 1, sum += 1); printf("sum %d", sum);