In compiled languages, I think using CONST would result in less memory usage and slightly faster runtime execution. CONSTS aren't variables, and therefore take up no space in the data, although they take up space in the code wherever they are used. Also, there isn't the need to fetch it from some other location at runtime, as it is part of the code. CONSTs are handled by the compiler at compile time. So, for example: DIM doublepi AS SINGLE DIM r AS SINGLE doublepi = 6.284 INPUT r PRINT r * doublepi In this case, space for the variable would be allocated, and the variable would have to be assigned the value at run time. Then, the PRINT r * doublepi statement would require fetching two variables. It could be rewritten as: CONST doublepi = 6.284 DIM r AS SINGLE INPUT r PRINT r * doublepi In this case, doublepi would not be a variable, so no space would be allocated for it. For the statement PRINT r * doublepi, only one variable would need to be fetched. The compiler would have replaced the reference to doublepi with the literal value 6.284 at compile time (or preprocessing time or whatever). So the value will be part of the code, which, I believe, would lead to faster execution. (It is still fetched from RAM, but as part of the code.) (I could be wrong on the matter of execution speed.) I guess if the literal values in the code were to take up more space than memory pointers, it would result in larger code size... Digressing a little: I don't know if Qbasic is smart enough to know, for example, in the case of: PRINT ((5 + 3) * 2) + 1 that since there are no variables or function calls, that it is all constant, that it could just do the math at compile time, and turn it into: PRINT 17 I imagine not, but I don't know. But if you were to do something like: CONST n = ((5 + 3) * 2) + 1 PRINT n Then I believe it would be forced to turn it into PRINT 17. Sometimes this can be useful. I often use CONSTs in cases where I don't want to use a variable, that is, the value of something does not need to change at runtime, but I don't want to use literals in a bunch of places, because I might want to change the value between runs. It is easier to change one CONST line, than to hunt down a bunch of literal constants scattered throughout the code, and risk changing a literal that coincidentally has the same value, but is otherwise unrelated. Also, CONST names can be descriptive, and can help document the code. crlf is more descriptive than 0xa0d. Well, that's my rambling defense of the CONST keyword... :-P Regards, Michael
|
| Response Title | Author and Date |
| a quick disclaimer | on Jun 24 |
| Yes I think you're correct | David on Jun 24 |