Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Delphi have any equivalent to C's volatile variable?

In C and C++ a variable can be marked as volatile, which means the compiler will not optimize it because it may be modified external to the declaring object. Is there an equivalent in Delphi programming? If not a keyword, maybe a work around?

My thought was to use Absolute, but I wasn't sure, and that may introduce other side effects.

like image 338
Jim McKeeth Avatar asked Oct 24 '08 00:10

Jim McKeeth


People also ask

Can volatile be a variable in C?

A volatile keyword in C is nothing but a qualifier that is used by the programmer when they declare a variable in source code. It is used to inform the compiler that the variable value can be changed any time without any task given by the source code. Volatile is usually applied to a variable when we are declaring it.

What is C volatile?

C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby.

Where volatile variables are stored in C?

on an AVR, both will probably be stored in SRAM. On an ARM, the volatile will be stored in SRAM and the const will probably be stored in flash. This is mainly because the AVR flash is not accessible as "normal memory" to C programs, and you can't put any variables there.

What is the difference between volatile and non volatile variable in C?

The volatile memory stores data and computer programs that the CPU may need in real-time, and it erases them once a user switches off the computer. Cache memory and RAM are types of Volatile memory. Non-volatile memory, on the other hand, is static. It remains in a computer even after a user switches it off.


1 Answers

Short answer: no.

However, I am not aware of any situation in which the conservative approach of the compiler will change the number of reads or writes if you follow this approach:

When reading a cross-thread visible location, save its value to a local before doing any further manipulation; similarly, restrict writes to a single assignment.

The Delphi compiler does not perform common subexpression elimination (CSE) on non-local location expressions when there are calls to non-inlined methods between the expressions, as the compiler doesn't do interprocedural optimization and thus it would not be correct even for single-threaded code.

So, you may want to use InterlockedExchange() to do your reads and writes to force this; additionally, this will cause a full memory barrier, so the processor won't reorder reads and writes either.

like image 83
Barry Kelly Avatar answered Sep 30 '22 15:09

Barry Kelly