Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain an example for a midterm C++

Tags:

c++

My teacher just gave this as one of several program examples for an upcoming midterm in C++. The code is:

//What does this program print?

#include <iostream>
using namespace std;

#define foo1( a )  a * a

int j = 6;

inline  int
foo2( int a ) 
{
    return a * a;
}

void
goo1( int& x )
{
    x = 3;
}

void
goo2( int  x )
{
    x = 3;
}

int main()
{
    int i, j = 12;

    cout << "foo1 = " << foo1( 3 + 2 ) << "\n";
    cout << "foo2 = " << foo2( 3 + 2 ) << "\n";

    i = 5;
    goo1( i );
    cout << "goo1 = " << i << "\n";
    i = 5;
    goo2( i );
    cout << "goo2 = " << i << "\n";

    cout << "  j = " <<   j << "\n";
    cout << "::j = " << ::j << "\n";
}

Can someone please explain how foo1 = 11. I've been experimenting with different numbers for an hour and I can't understand exactly how that is calculated.

like image 668
user2309865 Avatar asked May 05 '26 05:05

user2309865


1 Answers

foo1 is a macro. Macros perform strict find and replace, so foo1(3+2) is replaced with 3+2*3+2. Following order of operations, 3+2*3+2 = 3+6+2 = 11.

like image 63
avlouis Avatar answered May 06 '26 18:05

avlouis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!