gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > C volatile keyword

#163271 - Synthetic - Sun Sep 28, 2008 5:54 am

Quick C question for the gurus:

Is the const/volatile flag set seperately from the rest of the type when you typecast an object?

lets say I have:

volatile int *foo;
...
(long *)foo=bar;

is it still volatile when I cast it as a long? can I cast volatile seperately, like so?

(long *)(volatile *)foo=bar;

can one simply cast a pointer as volatile, will it automatically pick up a void if I do (volatile *)foo?

Thanks

#163272 - Dwedit - Sun Sep 28, 2008 6:38 am

I know you get compiler warnings or errors when you assign a volatile pointer to a regular pointer without casting.
_________________
"We are merely sprites that dance at the beck and call of our button pressing overlord."

#163375 - sajiimori - Wed Oct 01, 2008 12:14 am

const and volatile are part of the type, so if you cast them away, they're really gone.

(volatile*) is really short for (volatile int*), just like (unsigned*) is short for (unsigned int*). C++ compilers should give an error though, because implicit int is only supposed to work in C.

#163393 - Miked0801 - Wed Oct 01, 2008 5:15 pm

Which begs the question, why would you cast to/from volatile? It has a very specific use and casting doesn't make much sense with it.

#163397 - sajiimori - Wed Oct 01, 2008 6:05 pm

I guess a volatile u32* could be sensibly cast to a volatile u8*, and so on.

#163402 - Synthetic - Wed Oct 01, 2008 6:58 pm

What Sajiimori said, I have a memory address to a control register that I want to write to as a word and a dword, but mostly I was just curious.

#163403 - sgeos - Wed Oct 01, 2008 7:43 pm

Miked0801 wrote:
Which begs the question, why would you cast to/from volatile? It has a very specific use and casting doesn't make much sense with it.

You could force a read or a write that way.
Maybe you want to make a gameshark resistant program that is free to leave the values of certain data on registers most of the time, but is force read or written to now and then?
Then again, I doubt anyone actually does things like this.

#163454 - Miked0801 - Thu Oct 02, 2008 6:28 pm

If your casting vu8* to vu32*, you aren't adding or removing volatile from the mix and I completely understand that. I was thinking you were doing something like u32* to vu32* and back. That's just playing with the compiler and my mind :)

#163459 - Synthetic - Thu Oct 02, 2008 7:28 pm

yeah, in both cases it would be volatile, but I'm not using libnds typecasts, and I was getting tired of writing volatile everywhere =P