Learn point C language (34): function

Source: Internet
Author: User
Tags mul printf

1. Local Variables:

A local variable is also called an automatic variable, which declares that at the beginning of a function, it lives on the stack, and its life ends with the function returning.

#include <stdio.h>

int main(void)
{
  auto int i = 9; /* 声明局部变量的关键字是auto;因可以省略,几乎没人使用 */

  printf("%d\n",i);
  getchar();
  return 0;
}

2. Global variables:

The global variable declaration is outside the function body and should be in front of the function. Every function can use it, but global variables should be used sparingly.

#include <stdio.h>

void add(void);
void mul(void);

int gi = 3; /* 全局变量 */

int main(void)
{
  printf("%d\n",gi); /* 3 */

  add();
  printf("%d\n",gi); /* 5 */

  mul();
  printf("%d\n",gi); /* 10 */

  getchar();
  return 0;
}

void add(void) {
  gi += 2;
}

void mul(void) {
  gi *= 2;
}

The global variable is initialized to null, and the local variable is a garbage value before it is assigned:

#include <stdio.h>

int gi; /* 全局变量 */

int main(void)
{
  int i; /* 句柄变量 */

  printf("%d,%d\n",gi,i);

  getchar();
  return 0;
}

When a global variable has the same name as a local variable, a local variable is used:

#include <stdio.h>

int a = 111,b = 222;

int main(void)
{
  int a = 123;
  printf("%d,%d\n",a,b); /* 123,222*/

  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.