Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this statement mean?

I dont undestand this statement: f().array;... is a function call? or an access an attribute of the class? The statement data f(); is constructor's call? that's right?

#include <iostream>
using namespace std;

void f()
{
    cout << "hello!" << endl;
}

struct data 
{ 
    int array[10]; 
};

int main()
{
    data f();

    f().array;

    return 0 ;
}
like image 765
user3793107 Avatar asked Jul 29 '14 14:07

user3793107


2 Answers

The void f() and following lines define a function, f which takes parameters and return nothing.

The line data f(); declares a function f, which takes no parameters but return an object of type data. Since we've already seen the definition of f, we know that this line is actually lying to us, but the compiler lets it lie, because it wants to remain compatible with C where the definition could have been the one who's lying.

Got that?

UPDATE:

Originally, C didn't have the void keyword. So, to say that f() didn't return anything, you just left off the return type -- except the designers were lazy typists, so they decided to actually make "type not specified" mean "default to int" because they were returning ints more often than nothing. So, f() could be defining a function which returned nothing or an int. I think compilers were actually cool with you writing something like if (x==1) return 5; else return "five"; and letting the calling function figure out the return value.

Which brings us to data f();. Since you've just told the compiler that f() returns a data object, it trusts you, and ignores what you told it before. Of course, after the main() function, the new declaration of f() goes out of scope, and the compiler goes back to using the original signature for f().

The bottom line is, while legal, which is VERY BAD CODE (tm), and whoever wrote it should be slapped.

like image 114
James Curran Avatar answered Sep 24 '22 15:09

James Curran


I dont undestand this statement: f().array;... is a function call? or an access an attribute of the class?

Both. It calls the function f, then accesses the return value's array member (but does nothing with it, making the member access pointless).

The statement data f(); is constructor's call?

No, it's a function declaration. In this case, it should give an error because you've already declared f with void return type.

To declare an object, you want:

data f;          // default-initialisation: leaves the array uninitialised
data f{};        // value-initialisation (since C++11): zero-initialise the array
data f = data(); // value-initialisation (historic): zero-initialise the array
like image 25
Mike Seymour Avatar answered Sep 25 '22 15:09

Mike Seymour