1

the base checks for null character but aren't c++ strings not supposed to be null terminated? should the base case check for length of the string?

#include <bits/stdc++.h> 
using namespace std; 

// Function to find string which has 
// first character of each word. 
char first(string str, int i=0) 
{ 
    if (str[i] == '\0') 
         return 0; 
    if (isupper(str[i]))  
            return str[i]; 
    return first(str, i+1); 
} 

// Driver code 
int main() 
{ 
    string str = "geeksforGeeKS"; 
    char res = first(str); 
    if (res == 0) 
        cout << "No uppercase letter"; 
    else
        cout << res << "\n"; 
    return 0; 
} 
Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15
bunny bugs
  • 35
  • 7

2 Answers2

2

aren't c++ strings not supposed to be null terminated

std::string are (guaranteed to be) null terminated (since C++11).

should the base case check for length of the string?

It could be. But it doesn't need to be, because of the null termination.

eerorika
  • 232,697
  • 12
  • 197
  • 326
2

aren't c++ strings not supposed to be null terminated?

Since C++11, std::string is guaranteed to be null-terminated.


should the base case check for length of the string?

Yes, if you want to handle strings that contain null characters.

For instance,

string str("ab\0cD", 5);
Sid S
  • 6,037
  • 2
  • 18
  • 24
  • It should be done that way anyway, because that is the interface of the type. The code in the question clearly originates from an old C implementation. Yes, `std::string` is null terminated due to an abstraction leak that had to be baked into the standard, but I wouldn't accept at code review any code that iterated a `std::string` as does that in the question. – Lightness Races in Orbit Jan 12 '20 at 14:28