Function returns value

Let us figure out what the phrases «function returns a value», «return value type» and «void function» mean.

#include <string> #include <iostream> std::string reverse_words(std::string str) { std::string rev_str = str; int str_len = str.length(); int k = 0; int j = 0; for (int i = 0; i < str_len; ++i) { if ((str[i] == 0x20) and (str[i - 1] != 0x20)) { for (j = 0; j < (i - k); j++) { rev_str[j + k] = str[i - j - 1]; } k = i + 1; } else if ((str[i] == 0x20) and (str[i - 1] == 0x20)) { ++k; } // Check the last element of the string if ((i == str_len - 1) and (str[i] != 0x20)) { // if it is not a space we need to use additional reverse for (j = 0; j <= (i - k); j++) { rev_str[j + k] = str[i - j]; } } } for (int i = 0; i < str_len; ++i) { std::cout << rev_str[i]; } std::cout << std::endl; return rev_str; } int main() { std::string testString1 = "Visit website www.TopBicycle.ru"; std::string testString2 = "Visit website www.HeiHei.ru "; reverse_words(testString1); reverse_words(testString2); return 0; }

The result

tisiV etisbew ur.elcyciBpoT.www tisiV etisbew ur.ieHieH.www

The solution of a more competent programmer

std::string reverse_words(std::string str) { std::string out; std::string cword; for (char c : str) { if (c == ' ') { out += cword; out += c; cword = ""; continue; } cword = c + cword; } out += cword; return out; }

The code on this page was run with g++ 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Andrei Olegovich