C Language Nineth round: scope and storage type

Source: Internet
Author: User

C Language Nineth Round: scope and Storage type  

"Learning goals"

1. Local Variables

2. Global variables

3. Storage type

4. Memory

A: Local Variables

Local variables are also known as internal variables. A local variable is a description defined within a function.

Scope: Within a declared function or compound statement, a valid zone is also within a function or compound statement.

B: Global Variables

Global variables, also known as external variables, are variables that are defined outside of the function.

Scope: Entire with program Files

PS: Local variables and global variables are divided by scope.

#include <stdio.h> int numuber;  The global variable//scope              is the entire file//defines the print function. No parameter, no return value void print (void) {         float score;//local variable                      //scope is within                 the print function return;  As the end flag of print}int main (void) {         ///local variable score can have the same name as         float score;//local variable                      //scope is the main function within the         print ();                      return 0; }


C:auto the Use

Inside a function or compound statement, if the variable is not declared as a static storage type, it is called the auto variable

PS: C language provisions, the keyword auto can be omitted (by default, auto).

d:static the Use

(1) modifier variables (static area where memory exists)

(a) Static local variable: is a local variable modified with static.

PS: Static local variables are stored in the static data area, with the same life cycle as the program. It is important to note that static local variables can only be used within defined functions and only persist!

(b) Static global variable: A global variable modified with static.

PS: A static global variable can only be scoped to a file and cannot be referenced by another file.

(2) modifier Functions (static function, also called intrinsic function)

Add static to the function before it. The meaning of ' static ' here is not the means of storage, but the function is confined to this file

Function: Observe static local variable # include <stdio.h>//static function definition//define static print function, scope only in this text//return value is void, parameter is voidstatic void print (void) {    static intnum= 0;  The definition of static local variables       num++;//num=num+ 1;      printf ("%d\n", num);                                     Return The return type is void, so nothing is returned. This write can improve readability}  int main (void) {    //auto variable is defined                   floatscore= 99.0;  Equivalent to Autofloat score= 99.0;                                     The first call to the print function                   printf ("The value of Num after the first call:");                   Print ();                                       The second call to the print function                   printf ("After the second call, the value of num:");                   Print ();                      return 0; }


Operation Result:


We will find that the value of num is self-added based on the value of the previous call.

E:register variable (register variable)

A variable modified with register is the register variable. Register: This keyword requests the compiler to make the variables available in the CPU internal registers as much as possible rather than through memory addressing to improve efficiency. ( it is possible, but not absolute, because The number of registers of the CPU is limited!!) )

PS: Although registers are very fast, there are some limitations to using the Register modifier: The register variable must be a type that can be accepted by the CPU register. means that the register variable must be a single value, and its length should be less than or equal to the length of the integral type. The register variable may not be stored in memory, so the address of the register variable cannot be obtained with the fetch operator "&" .

F:extern the Use

The keyword extern can be placed before a variable or function to indicate the definition of a variable or function in another file

"Extending knowledge"

Take a look at this knowledge before you look at the procedure below. This is often used in custom header files.

(overall function) prevents header files from being repeatedly referenced   #ifndef textc_h     #define TEXTC_H   //content ...   #endif


testc.h in the file, note : This is a custom header file "

Use of the textc.h file//extern  #ifndef textc_h   //(overall function) prevents the header file from being repeatedly referenced #define TEXTC_H int    number=  100;float score= 99.9;char   ch= ' A '; #endif

main.cfile

#include <stdio.h> #include "textc.h"  //Custom header file. Hit "" means to first locate the header file in the current file directory  int main (void) {         extern int number;   Declares that number is defined. Same below     extern float score;     extern char ch;         printf ("number=%d\n", number);     printf ("Score=%.1f\n", score);     printf ("    ch=%c\n", ch);                 Return0;}    

main.c must be associated with testc.h together!

Operation Result:

G : Memory

memory can be divided into three parts: heap, stack and static area "Heap is heap, stack is stack"

  1. Heap: Memory allocated by the MALLOC series function. Its life cycle is determined by free or delete.                                                                                  features: flexible use, space is relatively large, but error-prone.
  2. Stack: saves local variables.                                                                                 The contents of the stack exist only within the function, and when the function is finished, it is destroyed on its own. Features: High efficiency, but with limited size.
  3. Static zone: Saves automatic global variables and static variables. The contents of the static zone are present throughout the lifetime of the program.

Program interpretation of Heap, stack, and static zones # include <stdio.h> #include <stdlib.h>//for function malloc () and exit () provide the original function//define the memory allocation function malloc, No parameter and no return value void Malloc (void) {         intnum= 100;//local variables, stored in the stack, the function is destroyed in the end of the memory                 Char*str;  Defines a char-type pointer variable for the use of the          //malloc function, allocating 100 bytes of space         str= (void*) malloc (num* sizeof (char));//coercion type conversion         if (str== NULL)         {                   printf ("Memory allocation failed \ n");                                     Exit (1);  Program Exit         }         //str dynamic memory allocation is successful and is stored in the heap.             return;} Defines a static global function that is statically int number= 1; stored in a static zone, the int main (void) {floatscore= 99.9 is destroyed only when the program ends  ;  Local variables, stored in the stack           return 0;}


H : Memory allocation function

"extended knowledge " must be "popular" before using these functions

1. size_t is the alias of Unsignedint because the size is not allowed to be negative.

2. void * (null type pointer) can be coerced to any type of pointer, but does not allow inverse operation!

3. sizeof () is the size of the byte, but not the dynamic allocation of memory.

4. void perror (const char * str); Print error message

(1) Use of malloc

Prototype: void* malloc (size_t size);

Allocates a size-sized byte memory and returns a pointer to the start of memory

malloc Use example # include <stdio.h> #include <stdlib.h>  //malloc,free.exit int main (void) {         Unsignedint num; Defines an unsigned int type variable         char*str;  Defines the char type pointer variable str                 num=100;  Assignment statement, assigning 100 to num                 //For STR allocating 100 bytes         str= (char*) malloc (num* sizeof (char));         if (str== NULL)//detect whether the allocation succeeds         {             perror ("Memory allocation failed \ n");                         Exit (1); Exit program         }         else         {                   printf ("Memory allocation succeeded \ n");         }                 Free (str);//Release allocated memory         Str=null;//assign NULL to Str to prevent it from being a wild pointer           return 0;}  

(2) Use of calloc

Prototype: void* calloc (size_t num, size_t size); Size is type, num is number

Allocates num* size memory space, initializes to 0, and returns a pointer to the start of memory

Use of Calloc # include <stdio.h> #include <stdlib.h> int main (void) {         unsignedint num;         Inti;         Int*array;  Defines the int type pointer                 num=10;                   Allocates memory of num*sizeof (int) size and is fully initialized to 0         array= (int *) calloc (num, sizeof (int));         if (array== NULL)         {                   perror ("Memory allocation failed \ n");                                     Exit (1); Exit program         }         else         {                   printf ("Memory allocation succeeded \ n");                                     for (i= 0; i< num; i++)                   {                            printf ("%d", array[i]); Can be the same as an array of access way range elements                   }         }                 //Release memory free         (arrays);         Array=null;           return 0; }

Operation Result:

Memory allocation succeeded

0 0 0 0 0 0 0 0 0 0

(3) Use of realloc

Prototype: void* realloc (void* ptr, size_t size);

Change the memory size of the pointer ptr

ReAlloc use # include <stdio.h> #include <stdlib.h>//malloc realloc,free,exit int main (void) {Unsig         Nedint num= 5;         inti= 0;         Int*array= NULL;                 Int*more_array= NULL;         array= (int *) calloc (num, sizeof (int));                                     if (array== NULL) {perror ("memory allocation failed \ n");         Exit (1);                 } printf ("Calloc: memory allocation succeeded \ n");         Assigns a value of array arrays for (i= 0; i< num; i++) {array[i]= i;         } printf ("Before allocating memory again:");         for (i= 0; i< num; i++) {printf ("%d", array[i]);         }//realloc new allocation of memory num=10;         More_array=realloc (Array, num* sizeof (int));                                     if (array== NULL) {perror ("memory allocation failed \ n");         Exit (1);         } printf ("\n\nrealloc: memory allocation succeeded \ n"); to the arrayMore_array assignment for (i= 0; i< num; i++) {array[i]= i;         } printf ("After allocating memory again:");         for (i= 0; i< num; i++) {printf ("%d", array[i]);         } free (array);                 Array=null; Return0;}

Operation Result:

calloc: memory allocation succeeded

before allocating memory again : 0 1 2 3 4

realloc: memory allocation succeeded

after allocating memory again : 0 1 2 3 4 5 6 7 8 9

(4) Use of free

Prototype: void free (void* ptr);

"Smile at the Fingertips" error is unavoidable, hope to get everyone's correction ^ ^

When reproduced, keep the original link http://codingit.howbbs.com and http://blog.csdn.net/mirrorsbeyourself

C language Nineth round: scope and storage type

Related Article

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.