Getting Started with C + + Classic-Example 4.10-using static variables to achieve accumulation

Source: Internet
Author: User

1: Static variable statics can be divided into static local variables and static global variables, the values of static local variables do not disappear after the function call, static global variables can only be used in the source file.

Static variables are static storage, which has the following characteristics:

(1) A static variable is defined within a function, released when the program exits, and is not released during the entire program's operation, that is, its lifetime is the entire source program.

(2) The scope of a static variable is the same as the automatic variable, and the definition within the function is used within the function, although the amount of change continues to exist, but it cannot be used, and it can continue to be used if the function that defines it is called again.

(3) The compiler assigns a 0 value to a static local variable.

The code is as follows:

//4.10.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>using namespacestd;intAddintx) {    Static intn=0; N=n+x; returnN;}voidMain () {inti,j,sum; cout<<"input the number:"<<Endl; CIN>>i; cout<<"The result is:"<<Endl;  for(j=1; j<=i;j++) {sum=Add (j); cout<< J <<":"<<sum <<Endl; }}
View Code

Operation Result:

Getting Started with C + + Classic-Example 4.10-using static variables to achieve accumulation

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.