Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login

const doesn't help most optimizing compilers, it only really helps prevent programmer clumsiness. Since most C/C++ compiler IR's are SSA-based all values are effectively const anyways at the level optimizations are performed whether or not they're mutable in the original source code.


view as:

Yes it's probably only really useful for parallel code, but it's always nice to make constant things const.

Why use "const int" there instead of #define? Far fewer issues with linkage and use in multiple files with #define.

No. If it's const it is static be default. This is the kind of shit that makes the windows api the royal pain in the ass it is.

>If it's const it is static be default.

If it's const at the file scope it's notably NOT static in the 'visible in the file scope only' sense of the word.

Try it, declare a const int at file scope in a C file and use it in a different C file with a extern prototype.


Because you can do this at runtime. I might have a different value everytime I call the function but this means that inside the fucntion the compiler knows the value can't change

Why ever use const at a file scope level. That's what I mean. #defines work SO much better there. Especially if being used outside the file.

const helps optimization in exactly one case: global data.

Adding const there requires the value to be a compile-time constant, and guarantees the optimizer can inline the value rather than reading from memory. Though it still can inline the value in many cases if it can prove the variable isn't modified.

Of course, this precludes conditional constructs such as the one proposed by excuse-me; that only works as a local var and the const is again irrelevant to the optimizer.


Legal | privacy