OK, I have some C++ code in a header that is declared like this:
void StreamOut(FxStream *stream,const FxChar *name = nil);
and I get: error:
'nil' was not declared in this scope
nil is a pascal thing, correct?
Should I be using NULL?
I thought they were both the same or at least Zero, no?
In C++ you need to use NULL, 0, or in some brand new compilers nullptr. The use of NULL vs. 0 can be a bit of a debate in some circles but IMHO, NULL is the more popular use over 0.
nil does not exist in standard C++. Use NULL instead.
Yes. It's NULL in C and C++, while it's nil in Objective-C.
Each language has its own identifier for no object. In C the standard library, NULL is a typedef of ((void *)0). In C++ the standard library, NULL is a typedef of 0 or 0L.
However IMHO, you should never use 0 in place of NULL, as it helps the readability of the code, just like having constant variables in your code: without using NULL, the value 0 is used for null pointers as well as base index value in loops as well as counts/sizes for empty lists, it makes it harder to know which one is which. Also, it's easier to grep for and such.
0 is the recommended and common style for C++
If you run a search through glibc you'll find this line of code:
#define NULL 0
It's just a standard way (not sure if it was published anywhere) of marking empty pointers. Variable value of 0 is still a value. Pointer pointing to 0 (0x0000... (it's decimal zero)) is actually pointing nowhere. It's just for readability.
int *var1, var2;
var1 = 0;
var2 = 0;
The above two assignments are not the same though they both look the same
just add at the beginning
#define null '\0'
or whatever you want instead of null and stick with what you prefer. The null concept in C++ is just related to a pointer pointing to nothing (0x0)..
Mind that every compiler may have its own definition of null, nil, NULL, whatever.. but in the end it is still 0.
Probably in the source you are looking at there is a
#define nil '\0'
somewhere in a header file..
I saw some comments on why not to use 0. Generally people don't like magic numbers, or numbers with meaning behind them. Give them a name. I would rather see ANSWER_TO_THE_ULTIMATE_QUESTION over 42 in code.
As for nil, I know Obj-C using nil as well. I would hate to think that someone went against the very popular convention (or at least what I remember) of NULL, which I thought was in a standard library header somewhere. I haven't done C++ in awhile though.
Related
I am trying to use a C++ library named MP4v2 in Swift. It is mostly working in that I can can call some functions, use some classes, etc.
I am having trouble with a particular function that returns a void pointer. It is NULL on failure, or some other value on success. There is a constant defined to check with, but neither that nor checking for nil works.
if file != MP4_INVALID_FILE_HANDLE {
throws /<path_to_project>/main.swift:19:12: Use of unresolved identifier 'MP4_INVALID_FILE_HANDLE', but it is DOES exist (other constants work).
if file != NULL just causes the same problem, and if file != nil never is true, even if the function failed. What am I doing wrong?
Looking at MP4v2 documentation, here is the definition of the macro to check for invalid handle:
#define MP4_INVALID_FILE_HANDLE ((MP4FileHandle)NULL)
The reason it cannot be used in Swift is because it involves a NULL. In fact, if you define something like
#define MY_NULL NULL
in your Objective-C(++) code and try to use it in Swift, Swift will suggest that you use nil instead.
The handle type MP4FileHandle is
typedef void * MP4FileHandle
So, if you are calling a function like
MP4FileHandle aCPPFunction()
You should be able to check the return value as follows in Swift:
let h : MP4FileHandle = aCPPFunction()
if h != nil
{
// The handle is valid and can be given as an argument to
// other library functions.
}
else
{
// The handle is NULL
}
I understand you tried this. It should work, please double-check. If for whatever strange reason this doesn't work for you, there are some other options:
Write a simple helper function in C, C++, Objective-C or
Objective-C++ to check if the handle is valid and return a integer
flag, which should be easily understood by Swift.
Check h.hashValue. If it is 0, then the handle is invalid,
otherwise it is valid. This is a bad undocumented hack, but it has
worked for me. I would stay away from this one.
I've got an interesting problem that I am sure someone would have come across. I am writing the front end UI in Objective C Cocoa, and the backend in C++. In C++ I have
#define NULL 0
Unfortunately, this has dire consequences for nil. Especially with nil terminated function calls as I now get this warning - "Missing sentinel in method dispatch", which I assume means it couldn't find the nil terminator. This is the only definition I could find for nil:
#ifndef NULL
#define NULL __DARWIN_NULL
#endif /* ! NULL */
#ifndef nil
#define nil NULL
#endif /* ! nil */
which seems to me that nil is NULL, and that my earlier define for NULL is messing everything up although I don't know how. The NULL is defined in C++ so that it can be platform independent. I have tried redefining NULL and nil, but nothing seems to take. Any suggestions on the correct way to go about this would be appreciated.
In either C or C++, attempting to define NULL yourself leads to undefined behavior. Sorry, but you're just allowed to do that. Instead of trying to define it yourself, you need to include one of the headers that already defines it for you.
Reminded me of this question I saw recently: How to wrap a C++ lib in objective-C?
So, what about:
#ifdef __cplusplus
#define NULL 0
#endif
You could #define it while it is being used within your .h/.cpp. Then, at the end of those files, #undef NULL so that the ObjC's definitions take over. That way the definition is cleaned-up.
You can also simply use 0 in C++ instead of NULL.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
I was going through a piece of C++ code and came across a code like
if (NULL != threadInfo)
{
...
...
}
I was just wondering is there any difference between using the expression
if (threadInfo != NULL)
{
...
...
}
what is said above.
While reading the first one reads " If NULL not equals to ThreadInfo" and the second one reads "If threadInfo not equals to NULL". To me the second one makes more sense.
No, there is no difference. In case of == there might be some difference. The thing is that if you accidentally write = instead of == the compiler will give an error in the first case.
if (threadInfo = NULL) //always false. The compiler will give you a warning at best
if (NULL = threadInfo) //Compiler error
I personally hate that practice and think it's better to write code that can be read in a normal human language, not Yoda language.
It's for safety, so you don't accidentally write
threadInfo = NULL
instead of
threadInfo == NULL
For the != there's no need to do this, but it's consistent.
If threadInfo is of a type that overrides operator !=, and the owner of that class has not provided a symmetric free function that handles the case where the two arguments are swapped, there might be a difference (there might also be a need to fire that programmer).
Otherwise, it's a matter of taste. Probably it will be preferred by people who write if(42 == answer) instead of if(answer == 42) -- this protects you from mistyping an assignment operator instead of an equals check. But since modern compilers warn you when you do that, it's debatable whether this approach offers anything.
There is no difference. The point of writing NULL != ... is that if you instead make a typo and write NULL = ... the code won't compile. If you had ... = NULL it could be a valid assignment and the error could go unnoticed (but most compilers detect this and warn you). Somebody once tried to insert a backdoor into the Linux kernel using this technique.
Also note that most persons don't code like that.
There is no difference, EXCEPT that the first option cannot be mistyped as:
if (threadInfo = NULL)
{
...
...
}
And some people don't know how to use compiler switches to check this (and some compilers don't have them).
No difference, this is so called Yoda coding convention.
if (NULL != threadInfo)
is equivalent to
if (threadInfo != NULL)
and to
if (threadInfo)
This is usually used as a convention, and has no distinct meaning by itself.
Because assignment occurs to lvals, and NULL is unassignable, this protects against the dreaded threadInfo = NULL when you meant threadInfo == NULL or threadInfo != NULL bug.
For more detail, see this wikipedia article section on left-hand comparisons
Both do the same thing. It is a style convention that was used to avoid typing mistakes as:
if (value=NULL) // assignment instead of == operator
{
}
These are exact equivalents in terms of logic.
The second is more intutive, when one may see the first is seen as more safe as it doesn't allows writing (threadInfo = NULL) erroneously, leading to a bug.
Null is a reference in the memory contains nothing but that nothing have an address to access it.
By that you can make a comparisons behind null to check if a certain object have a value or nothing.
I don't see any difference. However, the practice of writing NULL == someVar would save you from writing NULL = someVar if you forget typing the second =.
Is it good practice to check for null and check object properties in the same if statement?
Consider the following code:
if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
// Don't buy his records
}
This particular code is in java and I know the expression is evaluated from left to right so technically it won't throw a NullPointerException but in general is this good practice in any language?
As you are using an OR statement there will be a NullPointerException if jamesBlunt is null. You should use and, because if the left statement is false, the whole expression will be false.
Use:
if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
// Don't buy his records
}
When Java 7 is out, you could use the shortcut
if(jamesBlunt?.isReallyBad() {
// Don't buy his records
}
But until then the explicit check for null would be best practice. (In fact it would be best practice to not use jamesBlunt objects...)
I'll assume the || is a typo and you meant && :)
To answer your question: it depends.
Does it make sense for jamesBlunt to ever be null? If not, then it would be better practice to have something like this:
void buyARecord(Artist jamesBlunt) {
if (jamesBlunt == null) {
throw new IllegalArgumentException("James should never be null!");
}
}
If it does make sense for jamesBlunt to be null then your approach is fine, assuming null and isReallyBad mean the same thing semantically. If they mean different things semantically then you should probably not be combining them on one line.
You do need to be careful in other languages. Many (Java, C++, C# etc) will behave the same way, but some may evaluate from right-to-left or evaluate lazily. Take particular care with functional languages like Lisp and Scheme as they tend to behave differently to object oriented languages like Java and C#.
You want to use && instead of OR.
Yes, it is good practice to check for null in the same if statement, the alternative (nesting two ifs) is ugly because adds more indentation.
But checking before is also OK: specially if you want to do some error checking.
Personally, I would separate these. Null checking is the kind of thing one would do at the beginning of a function and is usually done to verify function parameters and are generally called "guard clauses". These checks will often raise an exception or return an error code as defined by the function.
These can lead to cleaner code below, avoiding multiple levels of nesting. It also prevents the need to repeat the null checks if there are other things you wish to test for on the object in question.
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.
Can we build similar feature for C/C++ (some kind of symbol table lookup)?
I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe).
You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously explicitly defined. There really is no such thing as an "unset" variable in C++.
Even if you say "int var;" and do not initialize it, the variable has a value, usually garbage, but it's still "set" in the PHP sense.
The closes I suppose would be the preprocessor's #ifdef and #ifndef which only checks to see if you've defined a variable using #define. But in my experience this is mostly used for omitting or adding code based on flags. For example:
// code code code
#ifdef DEBUG
// debug only code that will not be included in final product.
#endif
// more code more code
You can define DEBUG using #define to determine whether to include "DEBUG" code now.
Perhaps telling a bit more about what you're trying to do with the C++ equivalent of isset will give you a better idea of how to go about doing it "The C++ Way".
There is no direct means of doing this in the language. However, it is possible to do this sort of thing by using a map such as the following:
typedef std::map<std::string, int> variables_type;
variables_type variables;
variables["var"] = 1;
if(variables.find("jon") == variables.end())
std::cout << "variable, \"jon\" not set\n";
In order to make this a variable like those used in PHP or javascript, the implementation would need to use some sort of variant type.
Not really. You can't dynamically create variables (though you can dynamically create storage with malloc() et al, or new et al. in C++) in C. I suppose dynamically loaded libraries blur the picture, but even there, the way you establish whether the variable exists is by looking up its name. If the name is not there, then, short of running a compiler to create a dynamically loaded module and then loading it, you are probably stuck. The concept really doesn't apply to C or C++.
As said in other answers, in C++ variables are never undefined. However, variables can be uninitialised, in which case their contents are not specified in the language standard (and implemented by most compilers to be whatever happened to be stored at that memory location).
Normally a compiler offers a flag to detect possibly uninitialised variables, and will generate a warning if this is enabled.
Another usage of isset could be to deal with different code. Remember that C++ is a statically compiled language, and attempting to redefine a symbol will result in a compile time error, removing the need for isset.
Finally, what you might be looking for is a null pointer. For that, just use a simple comparison:
int * x(getFoo());
if (x) {
cout << "Foo has a result." << endl;
} else {
cout << "Foo returns null." << endl;
}
Well there is always Boost.Optional
http://www.boost.org/doc/libs/1_36_0/libs/optional/doc/html/index.html
which should almost do what you want.
Short answer: NO
Standard followup question: What problem are you really trying to solve?
You've got to separate two things here: variable declaration and variable contents.
As said in other answers, unlike PHP, C++ doesn't allow a variable to be used before it's declared.
But apart from that, it can be uninitialized.
I think the PHP isset function tries to find out if a variable has a usable value. In C++, this corresponds best to a pointer being NULL or valid.
The closest thing I can think of is to use pointers rather than real variables. Then you can check fro NULL.
However, it does seem like you're solving wrong problem for the language, or using wrong language to solve your problem.