Learn point C language (37): function

Source: Internet
Author: User
Tags printf

Non-pointer parameters (that is, pass-value parameters) are not modified to the original value, and const does not make sense to it.

Const is used only for pointers.

1. The first usage: const type * variable:

This usage restricts the values that the pointer points to.

#include <stdio.h>

int fun(const int *p) {
  *p += 1;  /* 只有去掉 const 这句才可以执行 */
  return *p;
}

int main(void)
{
  int num = 3;
  printf("%d\n",fun(&num));

  getchar();
  return 0;
}

2. There are, however, ways to circumvent this limitation:

#include <stdio.h>

int fun(const int *p) {
  int *p2 = p; /* 来个重名指针会绕过 const 的限制 */
  *p2 += 1;
  return *p;
}

int main(void)
{
  int num = 3;
  printf("%d\n",fun(&num)); /* 4 */

  getchar();
  return 0;
}

2. Second usage: type *const variable:

This usage will limit the pointing of the pointer; The following example attempts to modify the pointer and will not succeed.

#include <stdio.h>

void swap(int *const p1,int *const p2) {
  int *t = p1;
  p2 = p1;
  p2 = t;
}

int main(void)
{
  int x = 111;
  int y = 222;

  printf("%d,%d\n",x,y);
  swap(&x,&y);
  printf("%d,%d\n",x,y);

  getchar();
  return 0;
}

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.