Protect Global Data with const and volatile Type Qualifiers - MATLAB & Simulink (original) (raw)

In C, you use the type qualifier const to prevent code in an application from assigning a new value to a variable. In an application where an external actor (for example, a hardware device) can manipulate the value of a variable, you use the keyword volatile to prevent a compiler from optimizing the assembly code in a way that compromises the integrity of the variable value. You can also usevolatile to prevent a compiler from eliminating storage forconst data, such as a parameter that has a value that you want to tune during execution.

Maintain const Correctness for Arguments of Entry-Point Functions

When your external code calls a generated entry-point function and passesconst data through an argument (formal parameter) of the function, to make the corresponding argument in the function definition const, customize the execution (step) entry-point function interface.

Incorrect Results or Undefined Behavior When Passing Volatile Data to a Generated Function

The generated code can define and call functions other than model entry-point functions. For example, you can configure an atomic subsystem to appear in the code as a separate function. Also, lookup table blocks, such as n-D Lookup Table, typically yield separate utility functions.

When the generated code defines a function with an argument (formal parameter), the function does not protect against volatile data passed through the argument. Thus the function definition does not apply volatile to the argument, and when other generated code or your external code calls the function and passes in volatile data, the called function implicitly casts away the volatility.

When you execute code that calls a function accepting volatile data and the value of the data changes, you can get incorrect results or undefined behavior. To avoid this scenario, assign the value of a volatile variable to a non-volatile variable and pass the non-volatile variable as an argument to the function.