daniel mark

Hello all:

It is not good to return a reference or pointer to the local variable.

My question is the function 'beginComment' and 'endComment' are correct functions
If anyone is correct, why

Thank you

#include <iostream>
#include <vector>
using namespace std;

const char * beginComment()
{
return "[";
}

const char * endComment()
{
char * p = "]";
return p;
}


int main( )
{
cout << beginComment() << endl;
cout << endComment() << endl;
return 0;
}



Re: Visual C++ Language Are the following two functions correct?

Jonathan Caves - MSFT

Both functions look fine to me. You are not returning the address of a local variable - you are returning the address of a string: which are, in all C and C++ compilers that I know, always considered like global variables. Think of it as:

const char __str1[] = "[";
const char __str2[] = "]";

const char * beginComment()
{
    return __str1;
}

const char * endComment()
{
    const char * p = __str2;
    return p;
}

Note: the optimizer will probably get rid of p, as it is not really needed, leaving endComment looking more like beginComment.






Re: Visual C++ Language Are the following two functions correct?

Simple Samples

Jonathan Caves - MSFT wrote:
You are not returning the address of a local variable - you are returning the address of a string
I think you meant to say that they are literals, not strings. Literals are global but not all strings are.