Computer Science Canada Variable value |
Author: | Raknarg [ Sun Apr 15, 2012 3:40 pm ] | ||
Post subject: | Variable value | ||
Is there a way to have an if statement seeing if a variable has no value?
|
Author: | [Gandalf] [ Sun Apr 15, 2012 7:28 pm ] | ||
Post subject: | Re: Variable value | ||
As far as I remember, Turing doesn't default initialize variables. So it's more of a design issue, since trying to reference an uninitialized variable will fail at compile time. Usually you would initialize your value x to some sentinel value and check for that...
The key here is that -1 has no meaning for "normal" values of x. If the use case isn't trivial, you can consider making x an object, and keep track of its initialization state in a member variable. |
Author: | Raknarg [ Sun Apr 15, 2012 8:01 pm ] |
Post subject: | RE:Variable value |
Thats true, but the way my program wad weird, it was hard to reference specific variables. Linked lists are weird ![]() |
Author: | Dreadnought [ Sun Apr 15, 2012 10:24 pm ] | ||||
Post subject: | Re: Variable value | ||||
It is possible to detect if a variable is initialized or not. Turing saves one bit representation in each type for this, we just have to find out what it is and get Turing to check it. Here's a way of doing it for the more common built-in types:
If you find any bugs let me know. If you want to try stuff out yourself, here's a function that will print 32 bits.
Hope, this helps. |
Author: | Dreadnought [ Mon Apr 16, 2012 12:05 am ] | ||
Post subject: | Re: Variable value | ||
I'd like to add a check for pointers (might be helpful for lists).
|
Author: | Tony [ Mon Apr 16, 2012 12:10 am ] |
Post subject: | RE:Variable value |
pointers should be initialized (manually, if needs be) to null (which is 0). Null-Pointer Exceptions are much much much easier to figure out and solve, than random segfaults where the program just grabs a random piece of memory and runs with it as if it was a valid object, until something else breaks. |