Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a proper way to return NOT NULL pointer

Tags:

c++

pointers

I use an external C library in my C++ program and the library uses a callback function, that must return void*. The library checks if return value is not NULL, which means success.

So what is the best way to tell it that all is fine?

I use:

return reinterpret_cast<void*>(1);

but it looks ugly...

Edit: thanks for reply, i will stay with this:

static int success;
return &success;
like image 733
ShPavel Avatar asked Jan 23 '13 10:01

ShPavel


People also ask

How do I return a null pointer?

Just return '0' (zero). That is the representation of a null pointer in C++. nullptr would be better, but seriously, use std::find_if and preferably a std::vector<Person> without the pointer.

Can you return null in a pointer function?

A function that returns pointer values can return a null pointer when it is unable to perform its task. (A null pointer used in this way is analogous to the EOF value that functions like getchar return.) The start pointer steps over each character position in the input string.

How do you make sure an object is not null?

Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .

How do you check if a pointer is null or not?

Use Pointer Value as Condition to Check if Pointer Is NULL in C++ Null pointers are evaluated as false when they are used in logical expressions. Thus, we can put a given pointer in the if statement condition to check if it's null.


1 Answers

static int dummy;
return &dummy;

Strictly speaking, static is probably not required, but it feels a bit gauche to return a pointer to a local that's going out of scope.

EDIT: Note @sharptooth's comment. Strictly speaking, static is required.

like image 51
Marcelo Cantos Avatar answered Nov 09 '22 04:11

Marcelo Cantos