Skip to content

Behavior of reassignment to a const #38584

Closed
@FedericoStra

Description

@FedericoStra

I think that the semantics of const is not specified in the documentation clearly enough. In both Scope of Variables » Constants and Base » Essentials » Keywords » const the word "undefined" does not appear a single time.

What is the behavior of the following code?

const c = 0
const c = 1
print(c)

Is it really undefined behavior?

I see two major answers.

1. It is UB

Then the program above is allowed to do whatever it wants, including printing 0, printing 1, printing 2, printing "hello", not printing anything, crashing, hanging indefinitely, ...

According to the docs:

In some cases changing the value of a const variable gives a warning instead of an error. However, this can produce unpredictable behavior or corrupt the state of your program, and so should be avoided. This feature is intended only for convenience during interactive use.

However, if it is UB, then redefining a const is of no use whatsoever because there is no guarantee that it will do anything meaningful at all. Even during an interactive session, what follows has completely no sense because the whole behavior is undefined.

If this is the case, I think this point should be made more clear in the docs.

2. It is not UB, just "unspecified value"

Another possible interpretation is that when doing const c = some_new_value, from this moment on every reference to the name c can resolve to any value that the "constant" c has ever had, including some_new_value. This mean that the "value" of c may be unpredictable, maybe even unspecified, but the behavior of the program as a whole is not undefined in the strict sense.

Within this interpretation the following code is allowed to compute the surprising result (1, 0), but is not allowed to crash, hang, return 42, etc...

const c = 0
f() = c
f()
c = 1
g() = (c, f())
g() # currently outputs (1, 0)

Question

My personal interpretation from reading the docs is that the intent leans more towards option 2 (unspecified value), but I'm asking here to be sure (and possibly improve the documentation).

What is the correct interpretation of the meaning of const?

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsThis change adds or pertains to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions