insumity
insumity

Reputation: 5459

Initializing a Variable

Is it possible to do something like this in C?

typedef XXX bar;
void foo(bar i) {
    ...
}
main() {
    bar a;
    foo(a); // note!!, this is not foo(&a)
    // a is now initialized
}

Note that foo is a void function, otherwise by returning a new bar the problem could be easily solved. Furthermore, I have even if bar was a pointer, or a pointer to a pointer, e.g., typedef int ** bar, I don't see how foo could initialize a

My question was raised since I believe in GMP they do something similar. So in GMP you can have:

mpz_t a; 
mpz_init2(a); 
// a is now initialized

Upvotes: 0

Views: 145

Answers (3)

John Christofolakos
John Christofolakos

Reputation: 66

From http://gnu.huihoo.org/gmp-3.1.1/html_chapter/gmp_4.html:

mpz_t is actually implemented as a one-element array of a certain structure type. This is why using it to declare a variable gives an object with the fields GMP needs, but then using it as a parameter passes a pointer to the object.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 476930

Reference semantics can be implemented in C by using pointer parameters in functions and the address-of operator in argument lists:

void init(int * dst, int value) { *dst = value; }
//       ^^^^^^
//       function takes parameter by address, passed as a pointer

int main()
{
    int a;
    init(&a, 10);
    //   ^^
    //   caller passes address-of object
}

If you want a syntax that lexically omits the address-of operator, you can stick that part into a macro:

#define INIT_BY_REF(x, val) init_ref(&(x), val)

Now use: init_ref(a, 10)

Upvotes: 2

Mac O'Brien
Mac O'Brien

Reputation: 2907

It's only possible if the variable being initialized is a pointer or (typedef'd) array. I don't have experience with GMP, but that initialization function indicates to me that mpz_t is a typedef of a pointer or an array.

If the argument passed is a primitive or struct value, the function will use its own copy of the data and leave the variables passed to it untouched.

Upvotes: 0

Related Questions