2

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?

Community
  • 1
  • 1
Joel B
  • 12,082
  • 10
  • 61
  • 69
  • A pointer to an implicitly-created wouldn't cut it. According to its signature, it's entirely reasonable (even without casts and UB and the like) that `PlusTwoUsingPtr` writes to `*value`. –  Jun 06 '12 at 19:14

1 Answers1

5

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.

ouah
  • 142,963
  • 15
  • 272
  • 331