Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 41 - static

C Exercise 41 - static

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Learn how to use static to define static variables.

In the C language, the static keyword is used to declare static variables. Static variables differ from ordinary variables in that their lifetime and scope are different.

A static variable is initialized when it is declared, is initialized only once, and remains in existence throughout the entire lifetime of the program. A static variable declared inside a function can only be accessed within that function, while one declared outside a function can only be accessed within that file.

**Program Analysis:** In the following example, the foo() function declares a static variable x and initializes it to 0. Each time foo() is called, the value of x is incremented by 1 and the new value is printed. Since x is a static variable, it exists throughout the entire lifetime of the program, not just during the function call. Therefore, each time foo() is called, it can remember the value of x and increment it from there.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

void

foo

(

)

{

static

int

x

=

0

;

x

++;

printf

(

"

%d

\

n

"

,

x

)

;

}

int

main

(

)

{

foo

(

)

;

// Output 1

foo

(

)

;

// Output 2

foo

(

)

;

// Output 3

return

0

;

}

The output of the above example is:



1

2

3

100 Classic C Language Examples 100 Classic C Language Examples