C++ macro errors and inline functions | SoloLearn: Learn to code for FREE!


C++ macro errors and inline functions

Hello guys I was recently experimenting with macros but I found a macro error (Not Compilation Error) its like not having the correct output.Please explain the code. https://code.sololearn.com/cZ8TVan6Q3pe/#cpp [Edited] and also I wanna know why by using inline function I am getting different output while I have read that inline and macros both just replaces the code .

c++ c

9/16/2020 5:24:30 AM


13 Answers

New Answer


I got 3 as output. Is that what you get? What's the correct output you are expecting and why?


Ashmaupadhyay plz do not spam here. If you have a question, ask a new one.😇 And try to follow the guidelines 👇 https://www.sololearn.com/discuss/1316935/?ref=app


Where is the error? ((i >= 0)? (i) : -(i)) -> (x++ >= 0)? (x++) : -(x++); At x = 2; -> (2 >= 0)? (x++) : -(x++); Now, x incremented to 3. -> true? (x++) : -(x++); -> variable = (x++); -> variable = 3; Now, x becomes 4.


Akash by those () braces don't the x++ execution has to be first?


AteFish🇧🇩 read this article it's very well explained.. http://icarus.cs.weber.edu/~dab/cs1410/textbook/6.Functions/inline.html


AteFish🇧🇩 No, try something like this in Code PlayGround. int x = 5, y = (x++); printf("%d", y); // outputs : 5


Akash Please see the edited code and answer the questions


AteFish🇧🇩 Your code is working how it's suppose to be here. (But it's also compiler dependent) Try running this code, you'll notice that only after calling the inline function the value of x is incremented(since its post increment, try with pre increment ++x once, you'll get 3) #define un(i) (i>=0?i:-i) #include <iostream> using namespace std; inline int c(int x){ return x>=0?x:-x; } int main() { int a=2; cout<<un(a++)<<endl; int x=2; cout<<c(x++)<<endl; cout << x << endl; // x is 3 return 0; } I found a very good explanation here... https://stackoverflow.com/questions/11060968/using-the-post-increment-in-function-arguments#:~:text=When%20calling%20a%20function%20(whether,statements%20in%20the%20function%20body.


Akash Kevin ★ RKK How the inline functions and macros are same



AteFish🇧🇩 Your function is : inline int c(int x){ return x>=0?x:-x; } Here you passed argument as: int x = 2; -> c(x++); -> c(2); // first assign, then increment. -> return x >= 0? x : -x; -> return 2 >= 0? x : -x; -> return true? x : -x; -> returned 2 Note : the x in main() and x in c() are totally different.


Ashmaupadhyay with inline function😒


Writea c++ program that display" this is my first c++ program"