0

i have a code snippet in which i assign a value to a variable , var. In between the variable is acted upon left/right shift operations. Can such a variable ever become null.

Note that null is mostly defined as

#define null ((void*)0)

If it can't be null, then a check like:

if (var == null)

will give rise to dead code which will never be executed.

user3552519
  • 401
  • 4
  • 11
  • 1
    What is "mostly defined" in "null is mostly defined as" supposed to mean? – AnT stands with Russia Apr 25 '17 at 04:58
  • I would argue that in most C++ compilers, NULL is defined as 0. Obviously `null` is not a standard definition, so could be defined to anything. Without full code, it's hard to say, but I would argue that if the value becomes zero, then it will match the `null` or `NULL` definitions - albeit with warnings. – Mats Petersson Apr 25 '17 at 06:56

2 Answers2

2

Built-in shift operators are only applicable to values of integral or unscoped enum types. Built-in comparison to your null is only legal for values of pointer types. This means that results of built-in shift can never be compared to your null. (The only potential loophole here is the possibility to use shifts to form a null-pointer constant - an integral zero. But this is only possible in pre-C++11 version of the language. Not anymore.) The comparison is invalid.

In other words, there's no valid context in which this question can even arise. Your if will not produce "dead code" or "alive code". It simply won't compile at all.

But if you are talking about overloaded operators, then everything is possible. However, in that case your question is too broad to make sense.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

In C, you can compare interger values to pointers, so that code would produce a warning but probably work as expected. (Definitely not recommended, though)

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
  • With the exception of integral zero constant, you cannot legally compare integer values to pointers in C. C language has no such feature. – AnT stands with Russia Apr 25 '17 at 06:05
  • @AnT As we all know, there is a discrepancy between what is defined in the C language and what C compilers actually accept as source code. – Erich Kitzmueller Apr 25 '17 at 07:32
  • It depends on what you mean by "accept". C compilers are required to issue a diagnostic message in response to incorrect code. And they do. After that all bets are off. Is that "accept" or "reject"? – AnT stands with Russia Apr 25 '17 at 07:34
  • @AnT As long as compilation continues and results in an object file or executable file, I'd call it an "accept" for all practical purposes. (Please understand that I do not at all endorse ignoring warnings or writing code that leads to undefined behaviour - it's just something you have to expect to find in existing, apparently working code) – Erich Kitzmueller Apr 25 '17 at 08:24