LangProc / langproc-2017-cw

1 stars 4 forks source link

Dealing with const #17

Closed mahudu97 closed 6 years ago

mahudu97 commented 6 years ago

Since the purpose of const is to ensure a constant value, can we ignore the enforcing of const?

Since, as stated, all tests will be valid C, changing a const variable directly is invalid.

So my question is really whether or not we should care about the enforcing of the qualifier const.

EDIT: removed the part about pointers - I've realised its allowed but the behaviour is undefined so it doesn't matter what our compiler will do in that scenario.

fyquah commented 6 years ago

Assuming you are getting code that conforms to the C specification, it will have passed type-checking. I am not exactly sure what do you mean by "enforcing" a const, do you mean not mutating the location of the variable in? Do you mean not mutating the value in the register / location in stack? If that's the case, I'd imagine that you will not have to worry about it. (In fact, I can't imagine how would one not mutate register values for functions with many variables).

Many programming language features (const , class, struct, typedef) are really just artifacts for humans to understand and write better code.* Compilation passes often remove these redundant information with type erasure, among other compilation passes, before getting to code generation. For eg: a compiler can perform liveness analysis and allocate two variables (whether they are const or not) at the same location in the stack / in same registers -- would that quantify as disregarding the const quantifier? In essence, when it all comes down to allocating registers and stack space to variables in a function, compilers are free to do anything they want, as long as it behaves in a way compliant to the specification.

* Compilers use const to make particular optimisation. A constant integer, for example, can be (and will most often be) used as an immediate rather than a register value.