Comparing a char variable to empty char does not work

959 Views Asked by At

Say x is a character. Whenever I do if(x <> '') to know whether the variable is empty or not, it just does not work. However, when I attempt to do this if(x <> chr(0)), it does work. I have tried the same thing on two versions of the compiler : Free Pascal and Charm Pascal, but I am still facing the same problem.

1

There are 1 best solutions below

0
On BEST ANSWER

There is no such thing as an "empty char". The Char type is always a single character.

That character could be 1 byte AnsiChar representing a value from 0..255. (In Delphi and fpc, it could also be a 2 byte WideChar representing a value from 0..65535.) Either way it is always represented as '<something>'. That "something" must be a character value.

When you compare x <> Chr(0) you are taking the byte value of 0 and converting it to a Char so a valid comparison can be performed.


Side Notes

For Char to reliably have the concept "no value" requires storing additional information. E.g. Databases may have a hidden internal bit field indicating the value is NULL. It's important to be aware that this is fundamentally different from any of the valid values it may have if it's not NULL. Libraries that interact with databases need to provide a way to determine if a value is NULL.

You haven't provided any information about the actual problem you're trying to solve but here are some thoughts that may yield progress:

  • If you're dealing with user input, it may be more appropriate to compare with a space character ' '.
  • If you're dealing with characters read from a file, you should probably be checking number of bytes/characters actually read.
  • If you're trying to determine the end of a string it's much more reliable to use the Length() of the string.
    • (Though there are some environments that use the convention of treating Char(0) as a special character meaning "end-of-string".) But the convention requires allocating an extra character making the string internally longer than its text length. So the technique is not usable if the environment doesn't support it.
  • Most importantly, from comments it seems you might be struggling with the difference between empty-string and how that's represented as a Char. And the point is that it isn't. You need to check the length of the string.

E.g. You can do the following:

if (s <> '') then
begin
  { You now know there is at least 1 character in the string so
    you can safely read it and not worry about "if it has a value".}
  x := s[1];
  ...
end;