Reputation: 13140
Say I have a two functions like the ones below:
unsigned char PlusTwo(unsigned char value)
{
return (value + 2);
}
unsigned char PlusTwoUsingPtr(unsigned char *value)
{
return (*value + 2);
}
If I want to test the first function while I'm developing, no problem, all I have to do is this:
PlusTwo(8);
The compiler will automatically place a constant somewhere in memory for me. However, to test the second function, it gets more complicated. First I have to declare a variable, then pass the function the address of the variable:
unsigned char eight = 8;
PlusTwoUsingPtr(&eight);
This isn't horribly time consuming, but it is annoying (particularly in C89/ANSI where variables have to be declared at the beginning of a function block). Is there some trick that will allow me to just test this function in one line of code, having the compiler declare & place a constant somewhere for me to point to?
Upvotes: 2
Views: 90
Reputation: 145899
You can use a compound literal with a scalar type:
PlusTwoUsingPtr(&((unsigned char){8}));
Compound literal is a feature introduced in C99. For information the object is mutable (with static storage duration) and you can also modify it in your function.
Upvotes: 5