Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c - Pointer to literal value

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no way to do this directly in C89. You would have to use a set of macros to create such an expression.

In C99, it is allowed to declare struct-or-union literals, and initializers to scalars can be written using a similar syntax. Therefore, there is one way to achieve the desired effect:

#include <stdio.h>

void f(const int *i) {
    printf("%i
", *i);
}

int main(void) {
    f(&(int){1});
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...