The problem of function return value in C language

Source: Internet
Author: User

C language in the function of the return value of the problem, in the function of the local variables are mainly on the stack open, out of the function variable is recycled, for the function return is worth the problem, give the following a few more specific examples to illustrate:

  1. function return value is a local variable defined in the function

    This type of return value can be used in the main function, because it is worthwhile to return a local variable, it is worth a copy, and in the main function we need only this value, so it is possible, for example


  2. int fun (char *arr)

  3. {

  4. int num = 0;

  5. while (*arr! = ' \\0 ')

  6. {

  7. num = num * + *arr-' 0 ';

  8. arr++;

  9. }

  10. return num;

  11. printf ("%d", num);

  12. }

  13. int main ()

  14. {

  15. int tem = 0;

  16. Char *arr = "12345";

  17. tem = Fun (arr);

  18. printf ("%d", tem);

  19. System ("pause");

  20. return 0;

  21. }

  22. 2. The function returns the pointer variable defined in the function

  23. Char *fun ()

  24. {

  25. Char *arr = "1234";

  26. return arr;

  27. }

  28. int main ()

  29. {

  30. Char *tem = fun ();

  31. printf ("%s", tem);

  32. System ("pause");

  33. return 0;

  34. }

  35. This is also true in the process of operation.

  36. 3. Function cannot return the address of a local variable

  37. int *fun ()

  38. {

  39. int a = 10;

  40. Return &a;

  41. }

  42. int main ()

  43. {

  44. int *tem = Fun ();

  45. printf ("%d", *tem);

  46. System ("pause");

  47. return 0;

  48. }

  49. 4. Function also cannot return the first address of an array

  50. int *fun ()

  51. {

  52. int arr[] = {1, 2, 3, 4};

  53. return arr;

  54. }

  55. int main ()

  56. {

  57. int *tem = Fun ();

  58. System ("pause");

  59. return 0;

  60. }

This article is from the "local and static Variables" blog, reproduced please contact the author!

The problem of function return value in C language

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.