Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to literal value

Tags:

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?

like image 441
James Avatar asked Oct 14 '09 07:10

James


People also ask

What is a pointer literal?

Pointer literal (C++11) The only pointer literal is the nullptr keyword that is a prvalue of type std::nullptr_t . A prvalue of this type is a null pointer constant that can be converted to any pointer type, pointer-to-member type, or bool type. Parent topic: Literals.

Can integer literals be assigned to pointers?

The null pointer is the only integer literal that may be assigned to a pointer.

What is a literal value?

Literal values (constants) are exact values (alphabetic or numeric). These values are also the constants that you use in expressions, such as the numeric value 100, or the string "John Smith". You must enclose only string literals within quotes.

What is a literal value in C?

Literals are the constant values assigned to the constant variables. We can say that the literals represent the fixed values that cannot be modified. It also contains memory but does not have references as variables. For example, const int =10; is a constant integer expression in which 10 is an integer literal.


1 Answers

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\n", *i); }  int main(void) {     f(&(int){1});     return 0; } 
like image 139
alecov Avatar answered Oct 01 '22 13:10

alecov