Pointer to literal value

Viewed 14395

Suppose I have a constant defined in a header file

#define THIS_CONST 'A'

I want to write this constant to a stream. I do something like:

char c = THIS_CONST;
write(fd, &c, sizeof(c))

However, what I would like to do for brevity and clarity is:

write(fd, &THIS_CONST, sizeof(char)); // error
                                      // lvalue required as unary ‘&’ operand

Does anyone know of any macro/other trick for obtaining a pointer to a literal? I would like something which can be used like this:

write(fd, PTR_TO(THIS_CONST), sizeof(char))

Note: I realise I could declare my constants as static const variables, but then I can't use them in switch/case statements. i.e.

static const char THIS_CONST = 'A'
...
switch(c) {
  case THIS_CONST: // error - case label does not reduce to an integer constant
    ...
}

Unless there is a way to use a const variable in a case label?

12 Answers

These answers are all outdated, and apart from a comment nobody refers to recent language updates.

On a C99-C11-C17 compiler using a compound literal, http://en.cppreference.com/w/c/language/compound_literal, is possible to create a pointer to a nameless constant, as in:

int *p = &((int){10});

Here is another way to solve this old but still relevant question

#define THIS_CONST 'A'

//I place this in a header file
static inline size_t write1(int fd, char byte)
{
    return write(fd, &byte, 1);
}

//sample usage
int main(int argc, char * argv[])
{
    char s[] = "Hello World!\r\n";
    write(0, s, sizeof(s));

    write1(0, THIS_CONST);

    return 0;
}
Related