Problems with return values and return pointers in the C language

Source: Internet
Author: User
Tags printf reference

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.