简体   繁体   English

初始化变量

[英]Initializing a Variable

Is it possible to do something like this in C? 是否可以在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. 注意foo是一个void函数,否则通过返回新的bar可以很容易地解决问题。 Furthermore, I have even if bar was a pointer, or a pointer to a pointer, eg, typedef int ** bar , I don't see how foo could initialize a 此外,即使bar是一个指针,还是指向一个指针的指针,例如typedef int ** bar ,我也没有看到foo如何初始化a

My question was raised since I believe in GMP they do something similar. 我提出了我的问题,因为我相信GMP会做类似的事情。 So in GMP you can have: 因此,在GMP中,您可以:

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

From http://gnu.huihoo.org/gmp-3.1.1/html_chapter/gmp_4.html : 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. mpz_t实际上实现为某种结构类型的单元素数组。 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. 这就是为什么使用它声明变量为对象提供GMP所需字段的原因,然后将其用作参数将指针传递给该对象。

Reference semantics can be implemented in C by using pointer parameters in functions and the address-of operator in argument lists: 引用语义可以在C中通过使用函数中的指针参数和参数列表中的address-of运算符来实现:

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: 如果您想要一种语法上在词法上省略了address-of运算符,则可以将该部分粘贴到宏中:

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

Now use: init_ref(a, 10) 现在使用: init_ref(a, 10)

It's only possible if the variable being initialized is a pointer or ( typedef 'd) array. 仅当要初始化的变量是指针或( typedef )数组时才有可能。 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. 我没有使用GMP的经验,但是该初始化函数向我表明mpz_t是指针或数组的typedef。

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. 如果传递的参数是原始值或结构值,则该函数将使用其自己的数据副本,并保持传递给它的变量不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM