strings



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
#include <string>
#include <cstring>
#include <cmath>
using namespace std;
string foo(char str[],int n)
{
    cout<<"hi";
    if(n==0)
        return NULL;
    if(n==1)
    {
        string s;
        s=str[0];
        return s;
    }
   return "not found";
}
int main()
{
    char str[]="abc";
    int l=pow(2,strlen(str));
    cout<<l;
    string arr[1];
    foo(str,strlen(str));
}

my question is that if i put return statement at the end in comments the program goes into a runtime error,y is it so?is the return statement neccessary coz in other functions returning integer or float it is not neccessary to return them.
it is not neccessary to return them.
You should always return value from value returning functions. You just got lucky with your previous attempts and compiler decided to return primitive types through CPU registers. When you are trying to return a string it uses stack instead and as function does not place anything on it, it lead to stack corruption and crash.

TL;DR: failing to return a value from non-void function is undefined behavior and should be always avoided
In your foo function it is expecting a string to be returned, Im not sure if NULL is a string.

In your main function its expecting an int to be returned but you are returning nothing.

Trying fixing those 2 problems and see if it helps.
thnx a lot
Topic archived. No new replies allowed.