Embedded C language Common keywords

Source: Internet
Author: User


1.static keywords
This keyword is also mentioned earlier, and its role is powerful.
To gain insight into the static keyword, you first need to master the composition of the standard C program.
The standard C program has been composed of the following parts:
1) The body section--CPU executes the machine instruction part, namely your program. A program has only one copy; read-only to prevent the program from modifying its own instructions due to an accident;
2) Initialize the data segment (data segment)--All the global variables assigned the initial value in the program, stored here.
3) Non-initialized data segment (BSS segment)--global variable not initialized in the program; the kernel initializes this segment to 0.
Note: Only global variables are assigned to the data segment.
4) Stack-growth direction: top-down growth, automatic variables and the information (return address; Environment information) needed to be saved each time the function is called. This sentence is very important, often a pen question will ask what put in the stack is enough to explain.
5) heap--dynamic storage allocation.

In embedded C language, it has three functions:
Function One: In the function body, a variable that is declared static maintains its value in the process of the function being called.
The variable defined is called a local static variable: a local variable is defined as a local static variable by adding the keyword static before the local variable. That is, the variables defined in the function body as mentioned in role one above. In addition to the type character, the default is a local variable if no other keyword decorations are added. such as the following code:
void Test1 (void)
{
unsigned char A;
static unsigned char b;
...
a++;
b++;
}
In this example, variable A is a local variable and variable B is a local static variable. Function one illustrates the characteristics of local static variable B: In the function body, a variable declared as static (that is, a local static variable) maintains its value during the invocation of this function. What do you mean by that sentence? If you call the above function test1 twice in a row:
void Main (void)
{
...
Test1 ();
Test1 ();
...
}
Then make the program pause and read the values of A and B, and you will find that a=1,b=2. What's going on? Each time the Test1 function is called, the local variable A is reinitialized to 0x00, and then the a++ is executed, while the local static variable maintains its value during the call.
This feature is commonly used to count the number of times a function has been called.
Declare a local variable of the function and set it to the static type as a counter so that the function can be counted each time it is called. This is the best way to count the number of functions being called, because this variable is closely related to the function, and the function may be called in many different places, so it is difficult to count from the caller's point of view. The code is as follows:


void count ();
int main ()
{
int i;
for (i = 1; I <= 3; i++)
{
Count ();
{
return 0;
}
void Count ()
{
static num = 0;
num++;
printf ("I have been called%d", num, "times/n");
}
The output is:
I have been called 1 times.
I have been called 2 times.
I have been called 3 times.

Take a look at the detailed characteristics of the local static variable and notice its scope.
1) in-memory location: Static Storage Area
2) Initialize: Uninitialized global static variable is automatically initialized to 0 by the program (the value of the automatic object is arbitrary unless he is displayed initialized)
3) Scope: The scope is still a local scope, and when the function or statement block defining it ends, the scope ends.
Note: When static is used to modify a local variable, it changes the location where the local variable is stored and changes from the original stack to a static storage area. But the local static variable is not destroyed after it leaves the scope, but still resides in memory until the program is finished, but we can no longer access it.

Function two: within the module (but outside the function body), a variable declared as static can be accessed by the function used within the module, but not by other functions outside the module. It is a local global variable.
The variable defined is also called a global static variable: With the keyword static before the global variable, the global variable is defined as a global static variable. This is the static variable declared within the module (but outside the function body) mentioned in the above function.
Benefits of defining global static variables:
<1> will not be accessed by other files, modified, is a local locally variable.
<2> other files can use variables of the same name, and no conflicts will occur.
The detailed properties of global variables, attention scopes, can be compared with local static variables:
1) in-memory location: static storage (static storage is present during the entire program run)
2) Initialize: Uninitialized global static variable is automatically initialized to 0 by the program (the value of the automatic object is arbitrary unless he is displayed initialized)
3) Scope: Global static variables are not visible outside the declaration of his file. Start with the definition exactly to the end of the file.
When static is used to modify a global variable, it changes the scope of the global variable (which is invisible outside of declaring his file), but does not change its location or in the static store.

Function three: Within the module, a function declared as static can only be called by other functions within this module. That is, this function is restricted to the local scope of the module that declares it.

The defined function also becomes a static function: The function is defined as a static function by adding the keyword static before the return type of the function. The definition and declaration of a function is extern by default, but the static function is only visible in the file that declares him and cannot be used by other files.
Benefits of defining static functions:
<1> other files can define the same name function, no conflict
<2> static functions cannot be used by other files. It defines a local function.
Here I have been emphasizing the localization of data and functions, which has great benefits for the structure and even optimization of the program, and the larger effect is that localized data and functions can give people a lot of useful information to constrain the scope of data and functions. Private and public data/functions that are very focused on objects and classes in C + + are actually extensions of local and global data/functions, which also reflect the advantages of localized data/functions from the side.

Finally, the storage specifier, in standard C, the storage specifier has the following categories:
Auto, register, extern, and static
Corresponds to two storage periods: automatic storage period and static storage period.
Auto and register correspond to automatic storage periods. A variable with an automatic storage period is established when it enters the block that declares the variable, it exists when the block is active, and is revoked when it exits the block.
The keyword extern and static are used to describe variables and functions that have a static storage period. Local variables declared with static have a static storage duration (static storage duration), or a static range (static extent). Although his value remains valid between function calls, the visibility of its name is still limited to its local domain. A static local object is first initialized when the program executes to the declaration of the object.
2. CONST keyword
The Const keyword is also a frequently used keyword in a good program. The function of the keyword const is to convey very useful information to the person who is reading your code, and in fact, declaring a parameter as a constant is to tell the user the purpose of the parameter's application. By giving some additional information to the optimizer, using the keyword const may produce more compact code. Proper use of the keyword const allows the compiler to naturally protect those parameters that you do not want to change, and prevent them from being unintentionally modified by the code. In short, this can reduce the occurrence of bugs.
In-depth understanding of the Const keyword, you must know:
A. The const keyword-decorated variable can be considered to have a read-only property, but it is never equal to a constant. The following code:
const int i=5;
int j=0;
...
I=j; Illegal, resulting in a compilation error because it can only be read
J=i; Legal
B. The const keyword-decorated variable must be initialized at the time of declaration. The following code:
const int i=5; Legal
const INT J; Illegal, resulting in compilation errors
C. variables declared with const, although the allocation space is increased, can guarantee type safety. The const is originally derived from C + + and can be used instead of define to define constants. In the previous version of C, if you want to establish a constant, you must use a preprocessor:
#define PI 3.14159
Thereafter, regardless of where the pi is used, the preprocessor is replaced by 3.14159. The compiler does not type-check the PI, which means that it can be used to replace the values with unrestricted macros, which are often difficult to discover if they are inadvertently introduced by preprocessing. Also, we cannot get the address of pi (i.e. we cannot pass pointers and references to PI). The emergence of const, better solve the above problems.
D. In the C standard, const-defined constants are global.
E. It is necessary to understand the meaning of the following statement, I have repeatedly remembered it for a long time to remember, the method is: If you want to define a read-only property pointer, then the keyword const should be placed behind the ' * '.
Char *const CP; The pointer cannot be changed, but the pointing content can be changed
char Const *PC1; The pointer can be changed, but the pointing content cannot be changed
const char *PC2; Ibid. (The latter two declarations are equivalent)
F. Declaring a function passed in as const to indicate that this parameter is used only for the sake of efficiency, rather than to allow the calling function to modify the value of the object.
The parameter const is typically used in cases where the parameter is a pointer or reference, and only the input parameters are modified, and if the input parameter is in the "value Pass" mode, because the function will automatically generate a temporary variable for copying the parameter, the parameter does not need to be protected, so it does not have to be const decorated. Example:
void fun0 (const int * a);
void fun1 (const int & a);
When the function is called, the const constant is initialized with the corresponding variable, and in the function body, the part that is modified by the const is normally quantified, such as the parameter is const int * A, the content that the pointer that is passed in is not changed, and the content pointed to by the original pointer is protected, if the parameter is const int & A, you cannot change the referenced object that is passed in, protecting the properties of the original object.
G. Modifier function return value, which prevents the user from modifying the return value. (generally not used in embedded C, mainly for C + +)
H. Const eliminates the undesirable effects of preprocessor value substitution and provides a good form of type checking and security, where possible the use of Const can be of great help to our programming, provided that you have sufficient understanding of Const.
Finally, the two commonly used standard C library function declarations are examples of using Const.
1. String copy function: Char *strcpy (char *strdest,const char *strsrc);
2. Returns the string length function: int strlen (const char *STR);

3. Volatile keyword
A variable that is defined as volatile means that the variable may be unexpectedly changed so that the compiler does not assume the value of the variable. Precisely, the optimizer must carefully re-read the value of the variable each time it uses the variable, rather than using the backup stored in the register.
Because the access register is faster than RAM, the compiler generally makes optimizations to reduce access to external RAM. Like what:
static int i=0;


int main (void)
{
...
while (1)
{
if (i)
DoSomething ();
}
}


/* Interrupt Service routine. */
void isr_2 (void)
{
I=1;
}


The intent of the program is to call the DoSomething function in main when the isr_2 interrupt is generated, but since the compiler determines that I is not modified in the main function, it is possible to perform only one read operation from I to a register, and then each time the if judge uses only the "I copy" causes DoSomething to never be called.


If you add a volatile modifier to a variable, the compiler guarantees that read and write operations on this variable will not be optimized (definitely executed). I should also explain this in this example.


Generally, volatile is used in several places:


1, the change in the Interrupt service program for other programs to detect variables need to add volatile;


2, multi-tasking environment to share the logo should be added volatile;


3, Memory mapping hardware register usually also add volatile description, because each time it read and write may have different meanings;
Not knowing volatile content will bring disaster, which is also a key factor to differentiate between C language and embedded C language programmers. To emphasize the importance of volatile, once again an example is analyzed:
Code One:
int a,b,c;
Reading the contents of the I/O space 0x100 Port
A= Inword (0x100);
B=a;
A=inword (0x100)
C=a;
Code two:
volatile int A;
int a,b,c;
Reading the contents of the I/O space 0x100 Port
A= Inword (0x100);
B=a;
A=inword (0x100)
C=a;
In the above example, the code one will be optimized by the vast majority of compilers to the following code:
A=inword (0x100)
B=a;
C=a;
This obviously does not match the writer's purpose, there will be an I/O space 0x100 Port read phenomenon, if the increase of volatile, as shown in code two, the optimizer will not optimize any code.
From the above, the volatile keyword will reduce the compiler optimization effort, but it guarantees the correctness of the program, so in the appropriate place to use the keyword volatile is a test of programming skills.

4.struct and typedef keywords
In the face of a person's large-C + + program, only look at its use of the struct, we can evaluate the programming experience of its authors. Because of a large, C + + program, it is bound to involve some (or even large) combinations of data, which can combine data that is meant to belong to a whole. To some extent, will not use a struct, how to use a struct is to distinguish whether a developer has a rich development experience of the logo.
In the network protocol, the communication control, the embedded system C/s programming, we often want to transmit is not a simple byte stream (char array), but a variety of data combination of a whole, its representation is a structure.
Inexperienced developers tend to store all the content that needs to be transferred sequentially in a char array, using pointer offsets to transmit information such as network messages. This makes programming complex, error-prone, and once the control mode and communication protocol changes, the program will be very carefully modified.
Usage:
To define a struct type in C, use a typedef:
typedef struct STUDENT
{
int A;
}stu;
So when declaring variables, you can: Stu stu1;
If there is no typedef, a struct Student stu1 must be used to declare
The Stu here is actually the alias of the struct student.
In addition here can also not write Student (so also can't struct Student stu1;)
typedef struct
{
int A;
}stu;
One of the general functions of the struct keyword is that it can encapsulate the data, a little bit similar to C + + objects, and can object to some scattered attributes, which provides great convenience when writing some complex programs.
For example, to write a menu program, you need to know the menu index number of the menu, focus on the screen is the first item, display the corresponding menu item index, menu text content, sub-menu index, the current menu execution function operation. If the above entries alone, then the complexity of the program will be too large to imagine, if the number of menu layer is easy to implement, once the menu layer exceeds four layers, uh ~ I can not describe. A friend who has written a menu program may understand it deeply. At this time the struct struct begins to manifest its power:
Definition of structural body
typedef struct
{
unsigned char currentpanel;//menu index number for this level menu
unsigned char itemstartdisplay; Displays the menu entry index for the first item
unsigned char focusline; Focus on the screen is the first few items
}menu_statestruct;

typedef struct
{
unsigned char *menutxt; Menu text Content
unsigned char menuchildid;//sub-menu Index
void (*currentoperate) ();//function action performed by the current menu
}menuitemstruct;

typedef struct
{
Menuitemstruct *menupanelitem;
unsigned char menuitemcount;
}menupanelstruct;



Embedded C language Common keywords

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.