Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use 'function address == NULL' instead of 'false'?

Tags:

Browsing among some legacy code I've found such function:

static inline bool EmptyFunc() {     return (void*) EmptyFunc == NULL; } 

What are the differences from this one:

static inline bool EmptyFunc() {     return false; } 

This code was created to compile under several different platforms, like PS2, Wii, PC... Are there any reason to use the first function? Like better optimization or avoiding some strange compiler misbehavior?

like image 217
Vytis Valentinavičius Avatar asked Apr 25 '13 06:04

Vytis Valentinavičius


People also ask

Why can't I use the equal() function with null?

But even with that lib, field.equals (null) is still almost always an issue :P. Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null.

When to use null as an argument to an object?

The basic rule is simple: null should only be allowed when it makes sense for an object reference to have 'no value associated with it'. (Note: an object reference can be a variable, constant, property (class field), input/output argument, and so on.)

Why do we use null as the only reference in JavaScript?

It's the only object reference we can write literally in code. So Object a = null; Object b = null; means that a == b is true, because both variables contain the same object reference (the single universal blank one). if you invoke .equals () on null you will get NullPointerException

What is null in programming languages?

null is a fundamental concept in many programming languages. It is ubiquitous in all kinds of source code written in these languages. So it is essential to fully grasp the idea of null . We have to understand its semantics and implementation, and we need to know how to use null in our source code.


1 Answers

Semantically both functions are the same: they always return false*. Folding the first expression to a constant value "false" is completely allowed by the standard since it would not change any observable side-effects (of which there are none). Since the compiler sees the entire function it also free to optimize away any calls to it and replace it with a constant "false" value.

That is, there is no "general" value in the first form and is likely a mistake on the part of the programmer. The only possibility is that it exploits some special behaviour (or defect) in a specific compiler/version. To what end I don't know however. If you wish to prevent inlining using a compiler-specific attribute would be the correct approach -- anything else is prone to breaking should the compiler change.

(*This assumes that NULL is never defined to be EmptyFunc, which would result in true being returned.).

like image 130
edA-qa mort-ora-y Avatar answered Sep 20 '22 05:09

edA-qa mort-ora-y