user3905116
user3905116

Reputation: 23

gcc define temporary variable as function arguments

Is there a way to define a temporary variable for use as a function argument when calling a function? There is a function:

int hello(const int *p);

call it with

int a = 10;
hello(&a);

but the the var a won't be used after that, so I want them in one line, something like this:

hello(&(int a = 10)); // can't compile
hello(&int(10));      // can't compile

What is the right form to express this?

Upvotes: 2

Views: 308

Answers (3)

Abhishek Choubey
Abhishek Choubey

Reputation: 883

You can use the scope concept to do this.
Since "a" is an automatic integer, its scope is limited to the block in which it is declared.
Thus you can simply enclose the declaration and the function call inside a block, like this:

{
  int a = 10;
  hello(&a);
}

Upvotes: 0

Fiddling Bits
Fiddling Bits

Reputation: 8861

Answer

The proper syntax for a compound literal is as follows:

hello(&(const int){10});

Compound Literal

According to IBM:

The syntax for a compound literal resembles that of a cast expression. However, a compound literal is an lvalue, while the result of a cast expression is not. Furthermore, a cast can only convert to scalar types or void, whereas a compound literal results in an object of the specified type.

Upvotes: 3

user3159253
user3159253

Reputation: 17455

I think you have to define a first. But you can do it inside curly braces this effectively limiting scope of a:

{
   int a = 10;
   f (&a);
}

Upvotes: 3

Related Questions