Returning Arrays

What Does return {} Do in C++?

return {} sends back a value-initialized object of the return type: 0 for int, an empty vector or string, nullptr for pointers, and zeros for std::array.

On this page
  1. Short answer
  2. What the empty braces produce
  3. Example program
  4. Why not return nothing
  5. Where to use it
  6. Limits

Short answer

In C++, return {}; returns a value-initialized object of the function’s return type. The empty braces mean “no initial values,” so the returned object starts in its default zero or empty state. For an int, that is 0. For a std::string or std::vector, it is an empty object.

What the empty braces produce

Return type return {}; gives
int, double 0 or 0.0
bool false
any pointer, such as int * nullptr
std::string an empty string
std::vector<int> an empty vector
std::array<int, 3> all three elements set to 0

For a plain struct with no constructors, its scalar members are set to zero. If the class has a default constructor you wrote, that constructor runs instead. For pointers, the value is nullptr. What is a null pointer in C explains the same idea in C.

Example program

#include <iostream>
#include <string>

std::string find_name(bool found) {
    if (!found) {
        return {};  // an empty string
    }
    return "Ada";
}

int main() {
    std::cout << "[" << find_name(false) << "]\n";  // prints []
    std::cout << find_name(true) << '\n';            // prints Ada
}

The function returns an empty string when nothing is found. The caller can check the result with empty() to see whether the function found anything.

Why not return nothing

A function with a return type other than void must return a value. A bare return; works only in functions that return void. return {}; is a shorter way to write “the zero or empty value for this type,” and it works for any type that can be value-initialized.

Where to use it

Use return {}; when an empty or zero result is a reasonable answer, such as a search that finds nothing. If an empty value and a missing value mean different things in your code, std::optional can be a clearer choice, because it tells the caller whether a value exists at all.

Limits

  • You can’t use return {}; to return a C-style array, because arrays can’t be returned by value. How to return an array in C++ explains the workable options.
  • If a class’s default constructor is marked explicit, return {}; can fail to compile. A return statement with braces uses copy-list-initialization, and that doesn’t allow explicit constructors.

The complete guide to returning arrays

How to Return an Array in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

What Is long long in C++?

long long is a C++ integer type at least 64 bits wide. Learn its range, how to declare and print it, and when to use it instead of int, with examples.

long long 5 min read