function executed before main

following is what I wrote


#include <bits/stdc++.h>

using namespace std;

int sum(int arr[])
{ int k,d=0;
cout<<"function called";
int z=89;
return z;
}
int main()
{
int x,t,i;
cin>>x;
int are[x];
for(i=0;i<x;i++)
cin>>are[i];
int z=sizeof(are)/sizeof(are[0]);
cout<<"\none is="<<z<<"\n\n three is "<<sum(are);
return 0;
}

the input is
5
1 2 3 4 5
The out put is as follows

function is called
one is 5
three is 1

can anyone tellme why "function is called" is printing earlier ?
The order in which function parameters are processed is unspecified. So you can get different results on different systems (different compilers, for instance).

Try running the following program, but before you run it, take a guess as to what it will print.

1
2
3
4
5
6
7
8
9
#include <iostream>

char f() { std::cout << 'f'; return 'A'; }
char g() { std::cout << 'g'; return 'B'; }
char h() { std::cout << 'h'; return 'C'; }

int main() {
    std::cout << f() << g() << h() << '\n';
}

Also note that std::cout << f() << g() << h() << '\n' is basically syntactic sugar for
 
    operator<<(operator<<(operator<<(operator<<(std::cout, f()), g()), h()), '\n');

Last edited on
Because it's unspecified behaviour.
https://en.wikipedia.org/wiki/Unspecified_behavior

> cout<<"\none is="<<z<<"\n\n three is "<<sum(are);
The compiler is free to turn it into perhaps
1
2
int temp = sum(are);
cout<<"\none is="<<z<<"\n\n three is "<<temp;


The only thing you know is that sum(are) will be called at some point in the course of processing the whole cout statement.
What you can never know for sure is when that will be.

Here's another example.
1
2
3
4
5
6
7
8
int global = 0;
int foo ( ) {
  global++;
  return global;
}
int main ( ) {
  cout << global << " " << foo();
}

can anyone tellme why "function is called" is printing earlier ?
sum(...) needs to be evaluated before cout is finished.
How could cout otherwise actually print the result from sum(...)?

Actually the function is not executed before main(...).
With C++17, the behaviour is not unspecified (prior to that, it was).

C++17:
In a shift operator expression E1<<E2 and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2
https://en.cppreference.com/w/cpp/language/eval_order
int z=sizeof(are)/sizeof(are[0]); If your planning to move this inside sum() to compute the sum of the values in the array, it won't work. Inside sum() sizeof(arr) will return sizeof(int*). This is one reason why variable length arrays aren't standard C++ and why vectors are often preferable to arrays.
Topic archived. No new replies allowed.