+ 12

Can anyone tell me the difference between uses of square function and square as #define square (x) (x *x)?

Programming languages "C"

21st Apr 2019, 12:06 PM
David Rueda 🇪🇸
David Rueda  🇪🇸 - avatar
7 odpowiedzi
+ 8
A function is called and a #define literally replaces the code. 'printf("%d", square(x));' becomes 'printf("%d", (x*x));' if using a #define. The big problem is that #define can have nasty unintended side effects. If using the #define, square(x++) would become (x++*x++). Which would increment x twice while you expect it to be incremented only once and as you should know, incrementing the same variable twice in 1 expression is undefined behaviour, therefore square(x++) is undefined behaviour. Additionally square(rand()) would call the function twice and therefore generate 2 numbers. Now the square is a normal multiplication and not a square ( unless you get lucky ). Not to mention you have the cost of 2 function calls and whatever the cost of the function itself. There are also issues where square(x+5) would becomes (x+5*x+5). Since the + has lower precedence it becomes x+(5*x)+5 instead of (x+5)*(x+5). Some "genii" came up with ((x)*(x)) to fix this but which still have the aforementioned problems. None of these would be an issue if you used a normal function. So don't use a #define when you can use a function.
21st Apr 2019, 12:19 PM
Dennis
Dennis - avatar
+ 5
Dennis is probably right about those nasty outcomes that can occur many also there is one more when you use sqaure(x+1) then it would become (x+1*x+1) which is not the same as (x+1)*(x+1) But you can ask a question like what happened when I don't do this complicated stuff but i will only the simple stuff like square(n) [n is any number] Well there is one thing you should know like and of course first thing that when you are using the simple stuff you are not gonna be on this kind of situation and the output will be fine but when are going to write some bigger programs then macro have too characteristics that it will faster than functions but it will occupy much much more space if you are using that macro many times. But functions are the opposite they are slower than macro but it can occupy less space than the macro So you have to make the move to decide which one do you need to use and when.
21st Apr 2019, 12:51 PM
Sahil Bhakat
Sahil Bhakat - avatar
21st Apr 2019, 12:47 PM
David Rueda 🇪🇸
David Rueda  🇪🇸 - avatar
+ 4
If you mean the square(x + y) then yea, it becomes x + (y * x) + y. So not a square.
21st Apr 2019, 12:49 PM
Dennis
Dennis - avatar
+ 4
I don't use #define normally, but someone ask me, and then I want to explain it to him, but I had a little confusion. Thanks Dennis
21st Apr 2019, 12:54 PM
David Rueda 🇪🇸
David Rueda  🇪🇸 - avatar
+ 3
Функция square приводит к вызову кода предназначенного для вычисления квадрата - числа. Она может быть перегружена для корректного вычисления не только простых типов int, float и т.п., но и для структур/классов, умеющих возможность вычислять из себя квадрат. Директива же макроса #define позволяет подставить в качестве аргумента любой строковый литерал, из которого компилятор попробует собрать код умножения его самого на себя. При чем, вставляя копию этого кода, в каждом месте вызова макроса.
26th May 2019, 4:11 PM
Michail Getmanskiy
Michail Getmanskiy - avatar
+ 3
The square function calls the code for calculating a square - a number. It can be overloaded for correct calculation of not only simple types int, float, etc., but also for structures / classes that can calculate from a square. The macro directive #define allows to substitute as an argument any string literal from which the compiler will try to assemble the code of multiplying it by itself. At what, inserting a copy of this code, in each place of the macro call.
17th Jun 2019, 9:57 PM
Michail Getmanskiy
Michail Getmanskiy - avatar