2

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

could you please explain a little bit of you're solution. You're type casting 10 and then taking the address of an r-value. I didn't know this is possible?
@cartridgemeadow That's not a cast - cast-like syntax followed by a braced initializer list is a single piece of syntax forming an "object literal", i.e. the value, unnamed, in-place on the stack. You can take its address because the syntax implies that you want space to have been allocated for it (you are demanding that it physically exist somehow, which using a simple numeral doesn't). Normally it's used for structs, hence normally being called "compound" literal, but it works for any value including numbers.
@Leushenko and Fiddling Bits, thank you both for the thorough explanation and resources. I sincerely appreciate the application of something so cool! :0)
Although the compound literal has automatic storage duration, a const one could be placed in the same area as static const data. They could all be conflated too, in the same way as string literals can, e.g. &(const int){10} might be the same address for every time that expression occurs in your program.
3

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);
}

1 Comment

using scopes, very clever!
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.