0

In C, when I want to put number 5 at address 0x28, I can do it this way:

char* x = (char *) 0x28;
*x = 5;

If I want, I can do the same without declaring a variable:

*((char *) 0x28) = 5;

If I want that compiler treats this address as volatile, I can do it this way:

volatile char* x = (char *) 0x28;
*x = 5;

Can I do it without declaring a variable?

Edit: Let me explain why I want to do "*((char *) 0x28) = 5". I write a blinking LED hello world program for ATmega32U4 and I know that address 0x28 rules the pin to which my LED is connected. And it does work: the C code which you suggested compiles to correct machine code and the LED blinks.

9
  • 1
    (char *) 0x28 is undefined behavior (UB), unless 0x28 was the address of an object. Commented Feb 9, 2018 at 18:14
  • @chux, given that volatile is most often use for memory-mapped registers, that would be entirely plausible. Commented Feb 9, 2018 at 18:16
  • 2
    @zneak, plausible is not at all the same thing as well-defined. The C language does not guarantee that it is possible in any way to write a value to an arbitrarily-chosen machine address. In fact, it goes to some effort to avoid introducing any concept of machine addresses into the language at all. Pointers do not necessarily correspond to those. Commented Feb 9, 2018 at 18:22
  • 3
    @JohnBollinger, trying to drop the language lawyer hammer on people doing something so clearly invalid on a standard computer architecture that it has to be non-portable code for an embedded environment wed to its own C compiler isn't doing anyone a service. The C standard is not a ceiling: in fact, that document has a whole section on common extensions. Commented Feb 9, 2018 at 18:36
  • 1
    @zneak If the user is asking effectively how to do *((char *) 0x28) = 5;, then it is also likely the user (or others checking this post) do not realize code "doing something so clearly invalid" applies. There is no hammer involved, simply a statement that code may be UB. Commented Feb 9, 2018 at 18:40

1 Answer 1

3

It's simple:

*((volatile char *) 0x28) = 5;
Sign up to request clarification or add additional context in comments.

1 Comment

Good to leave volatile in should the address point to a hardware register.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.