int testA (void)
{
int b = 1 ;
return b;
}
char * testB (void)
{
char str[] = "abc" ;
return str;
}
int main()
{
printf( " the value of testA is %d \n", testA() );
printf( " the value of testB is %c ", *( testB() ) ) ;
}
For the return value:
Testa is in the stack with the main function, C + + creates a temporary variable at the end of Testa, and then copies the return value to the temporary
Variable.
printf ("The value of Testa is%d \ n", Testa ()) Outputs the value of the temporary variable, and B in Testa does not already exist.
For the return pointer:
This is the most complicated part. First, for the above scenario: Returns the first address of an array, because it returns char *
Type, so C + + will first create a temporary variable of type char *, and then assign the first address of the array to a temporary variable;
The array is also destroyed after the function ends, which means that the temporary variable points to an "undeclared address", which, fortunately, is not yet covered by other data, so it can also output the correct content.
In Testb, if replaced by char* str= "ABC"; return str; Since Str points to a section of the global data area's memory address, the temporary variable also points to the address after the function ends, so the compiler does not raise a warning. But such a method is not recommended.
Return reference:
This is the most efficient, it returns an object directly and does not produce a copy of the return value. But also pay attention to avoid returning a local reference.