What is the Java returning null equivalent in C++?

how to return null object in java
how to assign null value to object in java
return null c#
java null
java function to return null
java return null string
return empty object java
get return null java

I already know Java and am trying to learn C++ for for some other reasons. In a method in Java, if you don't have anything to return or there is an unreachable return line according to your logic but you just want to make the compiler happy, you just return null. For example:

public static int[] /* This can be any Object, and returning null would work */ 5() {
    for(int i = 0; i < 100; i++) {
        if(i == 5) {
            return new int[]{5}; // I don't know why you would want to do this, but I 
                                 // can't think of a better example.
        }
    }

    // The compiler will give an error because there is 
    // no return statement, even though it is guaranteed 
    // to return {5}. So, for convenience, do this:

    return null; 
}

However, if I do return NULL or even return nullptr in C++, it just gives an error. Is there any way I can get around this?

Like others have pointed out, there is nullptr. However returning a nullptr means your return value is a pointer which means you most likely have a heap allocation inside your function that you probably don't need.

Since C++ 17 we have std::optional which you could use as a return type for your function.

Given any non-reference return type T you can change that return type to std::optional<T> and instead of a nullptr you return either std::nullopt or {}.

Example:

std::optional<std::string> foo(int x)
{
    if (x > 10)
        return "greater 10";

    return std::nullopt; // or return {}
}

int main()
{
    auto str = foo(12);

    if (str)  // check if str actually has a value or if it's null
        std::cout << *str;  // dereference to get the actual string
    else
        std::cout << "no string returned";

    return 0;
}

Returning a "NULL reference" in C++?, I return an object if it exists or null if not. What would be the equivalent in C++ using references? Is there any recommended pattern in general? I saw some  There is no language-level equivalent for objects. One option is to create a "sentinel" object that is guaranteed to compare unequal to any "real" object, and return that: class ObjectType { public: static const ObjectType null; bool operator==(const ObjectType &rhs) const { /* need an appropriate comparison test */ }

That depends on the return type of your function. If you return int you have to return an int. If you return an int* you can return nullptr etc. You only get to return nullptr for pointer types.

The reason you're allowed to return null when you return Integer in Java is because that type is implicitly already a reference/pointer type to an int.

In the case where you want to satisfy the compiler and return a "default" you can :

return {};

Note that in your case you really want to be returning std::array, your example doesn't do what you think it does, prefer std::array over C arrays.

Stop Returning Null in Java, In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. Calling a method on a null reference  int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed. Nulls are assigned only to reference types, it means the reference doesn't point to anything.

First of all in C++ if you will write the the function like this:

struct Buffer {
};

Buffer calculateAndReturnBuffer() {
  // Some computations
  return Buffer{};
}

or something like this:

struct Buffer {
};

Buffer calculateAndReturnBuffer() {
  // Some computations
  return {}; // C++ uniform initialization
}

Buffer object is returned by value, it mean that according the basic rules in C++, it will be copied (but due to batch of optimizations it will not)

If you will try return null in this case:

struct Buffer {
};

Buffer calculateAndReturnBuffer() {
  // Some computations
  return nullptr; // or NULL
}

It will not work because nullptr is pointer type and NULL is define for 0 which is integer type and these objects cannot be converted to Buffer type You will need to do the following:

struct Buffer {
};

Buffer * calculateAndReturnBuffer() {
  // Some computations
  return nullptr; // or NULL
}

or something like this:

struct Buffer {
};

Buffer * calculateAndReturnBuffer() {
  // Some computations
  return {}; // C++ uniform initialization
}

Back to your question ... But in all cases you can use curly braces {}

Is it better to return NULL or empty values from functions/methods , An empty object implies data has been returned, whereas returning null clearly The analogous C# (anti-)pattern is the Try method: for example), another example would be the containsKey () method on a Map in Java). we like to try to make functions that when applied are exactly equivalent to their return value. hi i'm writing a java program and realised the main function returns void. so what is the equivalent of C's 'return 0' / 'return EXIT_SUCCESS'.

A quick and thorough guide to 'null': what it is, and how you should , null is a fundamental concept in many programming languages. support only value types, and some (e.g. C# and Java) support both of them. It would be tempting to say: Well, to differentiate, we return null if an allergy test  Most likely, it’s printing 0 which is the typical internal null pointer value but again it can vary depending on the C compiler/platform. You can try few other things in above program such as printf(“‘%c“,NULL) or printf(“%s”,NULL) and even printf(“%f”,NULL).

Is there a C++ keyword equivalent to Java null ?, I tried return 0 or NULL from a function that normally returns a class, but I got a compiler error, like: conversion from `int' to non-scalar type  Return a Null Object. The Null Object Pattern is described in the Gang of Four’s Design Patterns book. The intent of the pattern is to identify behavior that should occur when a null is encountered and encapsulate it using a static constant. Let's expand on the previous Blog class example:

Interesting facts about null in Java, Below are some important points about null in java which every Java are case-​sensitive in java, we can't write NULL or 0 as in C language. The comparison and not equal to operators are allowed with null in Java. This can //return false;. In a database, zero is a value. The value null means that no value exists. When used as a value, null is not a memory location. Only pointers hold memory locations. Without a null character, a string would not correctly terminate, which would cause problems.

Comments
  • What is the return type of your function?
  • Any object there is.
  • In C++, only pointers can be NULL, not objects (unless the object can be constructed from it.
  • You can just throw an exception. That will please the compiler, and as a bonus, give you some useful debug info in case the statement ever does get reached.
  • If control would fall off a non-void function without a return, the behaviour of the program is undefined. A C++ compiler can treat your above function identically to int * five(){ return new int[1] {5}; }
  • @jxh yes but that does a heap allocation aswell