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

+12

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

AteFish🇧🇩

13 Answers

New Answer

+6

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

+5

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

+4

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.

+3

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

+3

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

+2

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

+2

Akash Please see the edited code and answer the questions

+2

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.

+2

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

+1

+1

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.

+1

Ashmaupadhyay with inline function😒

-5

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