Author Topic: constants Array scope in "C'"  (Read 22467 times)

0 Members and 1 Guest are viewing this topic.

Offline NorthGuy

  • Super Contributor
  • ***
  • Posts: 3581
  • Country: ca
Re: constants Array scope in "C'"
« Reply #25 on: January 05, 2019, 01:22:32 am »
I still think it's an obscure case and it would have been better to forbid it as there is no real use to something like this when you can as well use a const pointer.

How's that obscure? You have a variable which is writable by some other thread, but is read only on your end. You declare it "const volatile". Now the compiler will not let you write it and will also ensure that it gets re-fetched every time you use it. How else would you do it?

The "const" keyword simply doesn't mean "constant", even though many people in this thread see them as interchangeable.
 

Offline NorthGuy

  • Super Contributor
  • ***
  • Posts: 3581
  • Country: ca
Re: constants Array scope in "C'"
« Reply #26 on: January 05, 2019, 01:25:58 am »
IMHO, standard C assumes a "const" variable to never alter its value during runtime.

The whole point of the standard is to define things as clearly as possible, so it would be impossible to have an opinion which is different from what the standard describes.

The problem isn't the standard but the fact that many people who are arguing about it have never read it.

Are you suggesting that a person who didn't read the standard is entitled to have his own opinion?
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4669
  • Country: us
Re: constants Array scope in "C'"
« Reply #27 on: January 05, 2019, 09:51:51 am »
Quote
Erm,  nope. If you want to put/access something in ROM (= Flash) on AVRs, you need to tag the pointer/variable using PROGMEM.
yes; no argument there.  The OP and I were talking about initialized variables declared as const but NOT explicitly placed in PROGMEM/Flash, which result in a RAM variable AND a ROM location that holds the initialization value, on both PIC8 and AVR.  The ROM value is copied to the RAM variable during the C startup code.
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1912
  • Country: de
Re: constants Array scope in "C'"
« Reply #28 on: January 05, 2019, 10:18:02 am »
How's that obscure? You have a variable which is writable by some other thread, but is read only on your end. You declare it "const volatile". Now the compiler will not let you write it and will also ensure that it gets re-fetched every time you use it. How else would you do it?
Well, "const volatile" should not work for this case. If you want to write to a variable from another thread, you need to declare it in a header. You need to use exactly the same qualifiers there which means the other thread can't write to it either. The only workaround is cheating, i.e. declare it non-const in another module but this is a direct way into linker/locator and consistency issues and won't survive any proper code review (or static code analysis which works on a project scope).

The "const" keyword simply doesn't mean "constant", even though many people in this thread see them as interchangeable.
A variable that is only declared "const" is constant for sure (can't be changed after initialization). The only surprise is that the standard allows the "volatile" and "const" qualifiers at the same time which seem to contradict each other. So this mixture of two contradicting qualifiers leads to "const" being diminished from "constant" to "read only by software". So yes, IMHO this is an obscure case and I never saw anybody using it in a professional (safety relevant etc.) environment.
Trying is the first step towards failure - Homer J. Simpson
 

Offline NorthGuy

  • Super Contributor
  • ***
  • Posts: 3581
  • Country: ca
Re: constants Array scope in "C'"
« Reply #29 on: January 05, 2019, 03:02:45 pm »
Well, "const volatile" should not work for this case. If you want to write to a variable from another thread, you need to declare it in a header. You need to use exactly the same qualifiers there which means the other thread can't write to it either.

You assume the "other thread" is programmed in C, which is not necessarily the case. These keywords are merely hints to the C compiler. If you declare something "const" the compiler must generate an error when you write to it. If you don't declare something "volatile", the compiler is allowed fetch the variable once and hold it in the register. Otherwise, these keywords don't change anything. This is specific to C (not even C++). A language may not have a notion of "const" or "volatile" at all (such as assembler, for example).

From the C viewpoint, if you cannot write something you declare it as "const", and if you think something may be changed by outside forces you declare it as "volatile". That is, if you are at the reading end of a mailslot, it looks like "const volatile" to you.

But, if you're on the other side of the mailslot, the situation is reverse - you can write, and the entity can never be changed by anything except your program. If you were writing a C program, you would not declare it neither "const" nor "volatile".
 

Offline andersm

  • Super Contributor
  • ***
  • Posts: 1198
  • Country: fi
Re: constants Array scope in "C'"
« Reply #30 on: January 05, 2019, 03:14:50 pm »
But, if you're on the other side of the mailslot, the situation is reverse - you can write, and the entity can never be changed by anything except your program. If you were writing a C program, you would not declare it neither "const" nor "volatile".
You would declare it volatile, to prevent the compiler from optimizing away repeated writes.

Offline janoc

  • Super Contributor
  • ***
  • Posts: 3958
  • Country: de
Re: constants Array scope in "C'"
« Reply #31 on: January 05, 2019, 03:46:15 pm »
Well, "const volatile" should not work for this case. If you want to write to a variable from another thread, you need to declare it in a header. You need to use exactly the same qualifiers there which means the other thread can't write to it either. The only workaround is cheating, i.e. declare it non-const in another module but this is a direct way into linker/locator and consistency issues and won't survive any proper code review (or static code analysis which works on a project scope).

You don't even need threads to have a valid use case for const volatile type.

I guess you have never seen a microcontroller register that is read-only for the user code but its value can change - typically registers for incoming UART/I2C/SPI/... data. Those are often memory mapped, so you would declare it as a pointer. Declaring that as const volatile is actually necessary because without the volatile qualifier the compiler could optimize the access out.


The "const" keyword simply doesn't mean "constant", even though many people in this thread see them as interchangeable.
A variable that is only declared "const" is constant for sure (can't be changed after initialization). The only surprise is that the standard allows the "volatile" and "const" qualifiers at the same time which seem to contradict each other. So this mixture of two contradicting qualifiers leads to "const" being diminished from "constant" to "read only by software". So yes, IMHO this is an obscure case and I never saw anybody using it in a professional (safety relevant etc.) environment.

That is actually incorrect and a ton of people fall into this trap, confusing const with something immutable.

Const only says that the lvalue (= memory address, even if it is a simple variable and not explicitly a pointer, variable is only a name for a memory address somewhere that you can retrieve using the & operator) you are using to access the data is read-only. It says nothing whatsoever about the value that the lvalue describes. Once you understand this, you will understand also why const volatile is perfectly fine and that a "const variable" can actually change after initialization.

Const is a type qualifier, it deals only with the type of the variable. What happens with the value described by that variable is outside of the scope of the standard. Look up pointer aliasing in C if you want to see real world examples.

That you have never seen anybody using this is not really an argument. There is plenty of all kinds of code out there in the wild, not all code is up to the NASA standards and if you live with such assumptions as the one above, you are pretty much setting yourself up for a nasty surprise at some point.

For example, look in these standard Cortex M3 headers (all ARM Cortex M3 MCUs use this), line 204 onwards:
https://github.com/ARM-software/CMSIS/blob/master/CMSIS/Include/core_cm3.h

Code: [Select]
/* IO definitions (access restrictions to peripheral registers) */
/**
    \defgroup CMSIS_glob_defs CMSIS Global Defines
    <strong>IO Type Qualifiers</strong> are used
    \li to specify the access to peripheral variables.
    \li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
  #define   __I     volatile             /*!< Defines 'read only' permissions */
#else
  #define   __I     volatile const       /*!< Defines 'read only' permissions */
#endif
#define     __O     volatile             /*!< Defines 'write only' permissions */
#define     __IO    volatile             /*!< Defines 'read / write' permissions */

/* following defines should be used for structure members */
#define     __IM     volatile const      /*! Defines 'read only' structure member permissions */
#define     __OM     volatile            /*! Defines 'write only' structure member permissions */
#define __IOM volatile /*! Defines 'read / write' structure member permissions */

Another example from a bit more recent CMSIS, showing use of this for I2C registers on LPC18xx series MCUs
https://github.com/ARM-software/CMSIS_5/blob/develop/CMSIS/Pack/Example/CMSIS_Driver/I2C_LPC18xx.h (scroll to the very bottom):
Code: [Select]
/* I2C Resource Configuration */
typedef struct {
  LPC_I2Cn_Type        *reg;                // I2C register interface
  IRQn_Type             i2c_ev_irq;         // I2C Event IRQ Number
  volatile uint32_t    *base_clk_reg;       // Base clock register
  volatile uint32_t    *pclk_cfg_reg;       // Peripheral clock config register
  const volatile uint32_t *pclk_stat_reg;   // Peripheral clock status register
  uint32_t              rgu_val;            // Peripheral reset value
  I2C_CTRL             *ctrl;               // Run-Time control information
} const I2C_RESOURCES;

So much about its use in "professional (safety relevant) environment".
« Last Edit: January 05, 2019, 04:12:43 pm by janoc »
 

Offline janoc

  • Super Contributor
  • ***
  • Posts: 3958
  • Country: de
Re: constants Array scope in "C'"
« Reply #32 on: January 05, 2019, 03:59:42 pm »
Are you suggesting that a person who didn't read the standard is entitled to have his own opinion?

Anyone can have opinion about whatever they want but that doesn't make them correct.
 

Online Jeroen3

  • Super Contributor
  • ***
  • Posts: 4639
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: constants Array scope in "C'"
« Reply #33 on: January 05, 2019, 04:44:38 pm »
static, const and volatile are the most complicated keywords in C.
Remember that C is a tool to write machine code. C doesn't know about what it runs on. You do.
Keywords only limit what you may do.
But it still is C, if you must you still may do so. You can work completely type-oblivious in C using void.

Types are actually a common source of bugs. And also a reason for debate. Hence why C++ is equipped with auto. Or some languages not even having types at all. (javascript)
But not all languages are easily compatible with every platform or intended function. You can't really use javascript for embedded or kernel drivers for example.
 

Offline janoc

  • Super Contributor
  • ***
  • Posts: 3958
  • Country: de
Re: constants Array scope in "C'"
« Reply #34 on: January 05, 2019, 06:59:00 pm »
static, const and volatile are the most complicated keywords in C.

You have obviously not seen the definition for restrict

(a slightly more understandable explanation: https://en.wikipedia.org/wiki/Restrict )

Types are actually a common source of bugs. And also a reason for debate. Hence why C++ is equipped with auto. Or some languages not even having types at all. (javascript)
But not all languages are easily compatible with every platform or intended function. You can't really use javascript for embedded or kernel drivers for example.

That's actually completely wrong, on several fronts (I will get to the auto keyword below).

Languages like Javascript (or Python, for ex.) of course do have types. They are just dynamically typed - i.e. the type is associated with the value (string, int, float, etc.), often using some sort of a tag stored with the data, not the variable that is used to refer to it. The "type" of a variable depends on what value has been assigned to it, so it could hold a string at one moment and an int two seconds later.

In contrast, languages such as C, C++, Java, Haskell and many others are statically typed - the type is known at compile time and does not normally change at runtime (ignoring type casting, type punning and similar).

Dynamic typing is of course convenient - no type declarations, you can store everything anywhere you want, etc. The downside is pretty much unmaintainable code unless extreme care is taken, the compiler will not warn you that you are passing a string to a function that expects numbers as arguments and similar -> lot of runtime bugs and problems. There are ways out of this, e.g. obsessive use of automated tests, using type annotations where you actually declare what argument types is your function expecting (Python, Lisp have these, Javascript doesn't) but all that requires programmer's discipline.

Static typing avoids these issues. For example Haskell is a strongly statically typed language where if you get the code to compile correctly, it is almost assured the code is also correct. That's because the strong typing and the very powerful type system that Haskell has allow the compiler to reason about the behaviour of your code in detail - much more than e.g. C/C++ compiler can. Static typing also allows for much more powerful optimization techniques than dynamically typed languages can perform.

Dynamicaly typed languages have to typically resort to things like JIT which actually "learn" what the types of the data are at runtime before being able to optimize the code. Whereas statically typed language can be optimized at compile time and often to much higher degree because the compiler is able to reason about the data - e.g. replace constants with values, eliminate constant expressions (think constexpr in C++) with precompiled values at compile time, eliminating entire files of code in the process.

Good example of this is the Kvasir library (https://github.com/kvasir-io/Kvasir) - it allows to write quite a bit of complex code e.g. initializing MCU registers, while checking that you don't write into bits that are not writeable or try to write an invalid value (e.g. 6bit value into 4bit register part - if you are doing it using bit manipulations you get no warning).

And all this (even multiple bit manipulations/assignments in a single register) typically compiles into a simple assignment because all this stuff is done as constant expressions and type manipulations (via C++ templates) so the compiler can optimize it. So you gain correctness, code readability and safety all the while not paying for it with runtime performance or code size. It costs only extra compilation time and possibly some horrific C++ error messages from the template instantiations if you screw up.

And re auto - C++ auto does not remove any types from the language. It is just a syntactic sugar so that one doesn't need to write the type when the compiler is able to deduce it automatically - which is only possible because the language is statically typed, so the compiler can compute what the resulting type of the expression will be. The variable is still typed the same as if you wrote the type there by hand.

Types actually help prevent the bugs, lack of the type information at compile time is the source of problems.

(And the fact that Javascript or Python aren't used for writing kernel drivers has nothing to do with types but a different language focus, even though both can and do run on embedded hw too. You are also not writing website code in C++. But that's a different debate, let's not turn this into a pissing context about the merits of this vs that programming language)
« Last Edit: January 05, 2019, 07:19:20 pm by janoc »
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf

 

- - -
-->