-1

Consider the following code

#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int n, i, j, max1 = -1000000000, max2 = -1000000000;
    cin >> n;
    long long int a[n];
    for (i = 0; i < n; i++)
    {
        cin >> a[i];
        if (a[i] > max1)
            max1 = a[i];
        j = i;
    }
    for (i = 0; i < n; i++)
    {
        if (a[i] > max2 && i != j)
            max2 = a[i];
    }
    cout << max1*max2;
}

Suppose max1=3,max2=6 then the last line of the program outputs '18on terminal ; we have not used any variable to store the result of this multiplication operation ,then where is '18 stored before being printed on screen. Is a new variable created by the compiler at compile time to store this value?

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36

1 Answers1

0

<< is an operator for cout. Operators are just like function, they takes parameters. So What happens is that max1*max2 is computed and passed as parameter to this guy: ostream& operator<< (long long val); Details on how that value is stored depends highly on how the compiler decides to optimize that specific call to operator<< for cout, but you can think it is stored on the stack somewhere at some point.

That said, max1*max2 is a temporary (an rvalue). It's up to the compiler where to store a temporary; the standard only specifies its lifetime. Typically, it will be treated as an automatic variable, stored in registers or in the function's stack frame, but again it's up to the compiler.

Think about what happens when you call something like the following:

int n=13;
int nn= sqrt(n*(n+1)*-n+5));

The value for n*(n+1)*-n+5) is first computed and passed as parameter to sqrt. The same thing is happening in cout<<max1max2


VLA are not part of the standard in C++ even if they are supported by means of an extension by both g++ and clang++. Consider using a container instead. More details here.

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36