Embedded C second task

 

1.Typedef

definition:

typedef is a key word of C language. It is used to define a new name for a data type.

effect:

One is to give variables a new name that is easy to remember and has clear meaning. The other is to simplify some complex type declarations.

typedef unsigned char BYTE;

After this type is defined, the identifier BYTE (usually uppercase to remind the user) can be used as the abbreviation of the type "unsigned char", for example:

BYTE  b1, b2;

For example (using this new data type to directly define structural variables): from: https://www.runoob.com/cprogramming/c-typedef.html

#include <stdio.h>
#include <string.h>
 
typedef struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} Book;
 
int main( )
{
   Book book;
 
   strcpy( book.title, "C course");
   strcpy( book.author, "Runoob"); 
   strcpy( book.subject, "programing language");
   book.book_id = 12345;
 
   printf( "Book title : %s\n", book.title);
   printf( "Author : %s\n", book.author);
   printf( "Book category : %s\n", book.subject);
   printf( "book ID : %d\n", book.book_id);
 
   return 0;
}

Output is:

Book title : C course
 Author : Runoob
 Book category : programing language
 book ID : 12345

Difference from #define:

typedef is limited to defining symbol names for types, #define can define aliases not only for types, but also for values. For example, you can define 1 as ONE.

typedef is interpreted by the compiler, and #define statements are processed by the precompiler.

Typedef is a new name for a type. Typedef conforms to the (C language) scope rule. The scope of the variable type defined by typedef is limited to the defined

Functions or files (depending on the location of the variable definition), while macro definitions do not have this feature.

#Define performs a simple string replacement. #define macro definition can use #ifdef, #ifndef, etc. to make logical judgment, and #undef can also be used to cancel the definition

#No semicolon after define and semicolon after typedef.

1. For example (when several variables are defined continuously, typedef can ensure that all variables defined are of the same type, while #define cannot):

typedef char* pStr1;
#define pStr2 char* 
pStr1 s1, s2;
pStr2 s3, s4;

In the above variable definitions, s1, s2 and s3 are all defined as char * types; However, s4 is defined as char type, and the relevant code after replacement is equivalent to:

char* s3, s4;

After using typedef to define a new type pStr1 for char *, the relevant code is equivalent to:

char *s3, *s4;

 

2. For example (simplify complex declarations and specify multiple objects at the same time):

char* pa, pb;

The above formula only declares a pointer to a character variable and a character variable;

typedef char* PCHAR;
PCHAR pa, pb; 

The above formula declares two pointers to character variables, which reduces the occurrence of errors.;

3. For example (define platform independent types):

On the target machine

typedef long double REAL; \\It's called a definition REAL Floating point type of

On machines that do not support long double, the typedef will look like this:

 typedef double REAL;

Moreover, on machines that do not even support double, the typedef will look like this:

  typedef float REAL; 

Total: when cross platform, just change the typedef itself without any modification to other source codes. Examples come from http://blog.sina.com.cn/s/blog_4826f7970100074k.html 

4. For example (an important question about typedef): boss Name: zw1996 Title: #define is different from typedef?

#include <stdio.h>
 
typedef char *pStr;
 
int main(void)
{
	char string[4]="abc";	//First line of code
	const char *p1=string;	//Second line of code
	const pStr p2 = string; //Third line code
	p1++;					//Line 4 code
	p2++;  					//Line 5 code 
	
	return 0;
}

Report an error (error: increment of read only variable 'P2');

The fifth line of code p2 + + has an error. This question reminds us that unlike #define, typedef is not a simple text replacement. In the above code

const pStr p2 is not equal to const char * p2. const pStr p2 and pStr const p2 are essentially the same. They are read-only variables

The limitation is that the data type of variable p2 here is defined by ourselves rather than the inherent type of the system. Therefore, const pStr p2 contains

The meaning is: the variable p2 whose data type is limited to char * is read-only, that is, char* const p2, indicating that p2 is a constant pointer to char type,

So p2 is not modifiable, so p2 + + error.

2. Structure

definition:

A structure is a data set composed of a series of data items of the same type or different types. These data items are called members of the structure.

When we want to build a student information management system, we need to save the student's name, student number, age and other information. What should we do?

(use the structure in three ways) boss Name: Embedded hodgepodge Title: [C language notes] structure

https://blog.csdn.net/zhengnianli/article/details/87568902

// Create structure template struct student
struct student
{
char *name;  // Student name
int num;     // Student number
int age;     // Student age
};

// Use this structure template to create three variables stu1, stu2 and stu3
struct student stu1, stu2, stu3;

Here, student is the structure name, which is defined arbitrarily, but try to give a meaningful name. It is equivalent to

A template that can be used to define variables stu1, stu2, stu3. Don't forget struct when defining.

// Define three structural variables stu1, stu2 and stu3
struct
{
char *name;  // Student name
int num;     // Student number
int age;     // Student age
}stu1, stu2, stu3;

Relative to method 1, the structure name is omitted here. Although it is more concise, because there is no name, you can't use this structure to define new variables later.

// Rename the structure template struct student to student
typedef struct student
{
char *name;  // Student name
int num;     // Student number
int age;     // Student age
}student;

// Use student to create three structural variables stu1, stu2 and stu3
student stu1, stu2, stu3;

Here, use typedef to define an alias student for the structure template struct student, and use typedef to create an alias for the structure.

About the location of its struct declaration

For example (if the declaration is placed outside any function, the optional tag can be in this file, and all functions following the declaration can be used):

For example (if this declaration is inside a function, its tag can only be used internally and after its declaration):

About and typedef

struct
{
    char title[MAXTITL]; 
    char author[MAXAUTL];
    float value; 
}library;
//Note that instead of defining and declaring structure types, you can directly create structure variables, and the compiler will allocate memory;
//In this way, the identifier, that is, the structure name, can be omitted, but it can only be used once; Because this is; Procedure for declaring a structure
  And the process of defining structural variables; And a member variable is not initialized;
//If you want to use a structure module multiple times, this will not work;
use typedef Define a new type name to replace the existing type name, that is, rename the existing type;
The general format is; typedef Existing type and new type name;
typedef int Elem; 
typedef struct{
    int date;
    .....
    .....
}STUDENT;
STUDENT stu1,stu2;

Summarize the definition of structural variables;
1;First define the structure type, and then define the structure variable;
The format is; struct Structure name and variable name list;
struct book s1,s2,*ss;//Note that the struct class must be defined before this
 Then define the variable;
2;Define structure variables while defining structure types;
The format is;
struct Structure name
{
Member list;
}List of variable names;//Here, the structure name can be saved, but try not to save it;
struct book
{
    char title[MAXTITL];//A title title represented by a string; 
    char author[MAXAUTL];//A string representing the author author; 
    float value;//A floating-point value price;
}s1,s2;
3,Directly defining the structure type variable is the case where the structure name is omitted in the second case;
This method cannot specify the structure type name, but directly defines the structure variable, and
 It is applicable when the structure variable is used once. The structure type without structure name cannot be reused,
In other words, the following program can no longer define this type of variable unless it is written again.

Initialization structure

Initialization and array variables are as follows:

int count = 0;
int arr[7] = {0,1,2,3,4,5,6};

Structural variables are as follows:

struct student stu1 = 
{
  "zjw", // name:
  520,   // Student No.: 520
  20     // Age: 20
};

Total: all initialization items are separated by commas

Another example:

#include <stdio.h>
 
struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book = {"C language", "RUNOOB", "programing language", 123456};
 
int main()
{
    printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book.title, book.author, book.subject, book.book_id);
}

Output result:

title : C language
author: RUNOOB
subject: programing language
book_id: 123456

Access structure members

Access to structure members requires the help of the structure member operator - point (.) Structure variable name Member name;

#include <stdio.h>

typedef struct student
{
 char *name;  // Student name
 int num;     // Student number
 int age;     // Student age
}student;

int main(void)
{
 student stu1;  // Define a structure variable stu1
 
 /* Assign a value to the member of the structure variable stu1 */
 stu1.name = "ZhengNianJun";
 stu1.num = 520;
 stu1.age = 23;
 
 printf("\n============================================\n");
 printf("My name is %s\n", stu1.name);
 printf("My num is %d\n", stu1.num);
 printf("My age is %d\n", stu1.age);
 printf("============================================\n");

 return 0;
}

Another example:

#include <stdio.h>
#include <string.h>
 
struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};
 
int main( )
{
   struct Books Book1;        /* Declare Book1 of type Books */
   struct Books Book2;        /* Declare Book2 of type Books */
 
   /* Book1 Elaborate */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Nuha Ali"); 
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;
 
   /* Book2 Elaborate */
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Zara Ali");
   strcpy( Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;
 
   /* Output Book1 information */
   printf( "Book 1 title : %s\n", Book1.title);
   printf( "Book 1 author : %s\n", Book1.author);
   printf( "Book 1 subject : %s\n", Book1.subject);
   printf( "Book 1 book_id : %d\n", Book1.book_id);
 
   /* Output Book2 information */
   printf( "Book 2 title : %s\n", Book2.title);
   printf( "Book 2 author : %s\n", Book2.author);
   printf( "Book 2 subject : %s\n", Book2.subject);
   printf( "Book 2 book_id : %d\n", Book2.book_id);
 
   return 0;
}

The output result is:

Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

The boss writes well https://blog.csdn.net/zw1996/article/details/53844585

3. Macro definition

Let's start with an example:

Macro function form:

#Define max (a, b) ((a) > (b) (a): (b)) / / why are there so many parentheses here? I'll talk about it later

Common function form:

int max(int a, int b)
{
     return (a > b a : b)
}

The example of operator priority problem can be: boss Name: Full city, glazed moon Title: C language: macro definition function

#define SQUARE_SUM(x,y) x*x+y*y
#include <stdio.h>
 
int main()
{
    int i = 1,j = 2,k ;
    k = SQUARE_SUM(i+1,j);
    printf("%d",k);
    return 0;
}

Many people may calculate as follows: 2 * 2 + 2 * 2 = 8, which is actually wrong. The reason is that the program is only replaced, that is, 1 + 1 * 1 + 1 + 2 * 2 = 7

To achieve a result of 8, it should be written as follows:

#define SQUARE_SUM(x,y) (x)*(x)+(y)*(y) / / pay attention to the parentheses here!!
#include <stdio.h>
 
int main()
{
    int i = 1,j = 2,k ;
    k = SQUARE_SUM(i+1,j);
    printf("%d",k);
    return 0;
}

Other knowledge points this article is detailed and easy to understand https://blog.csdn.net/qq_41865229/article/details/86746707

4. Conditional compilation

#define defines a preprocessing macro
#undef: undefine macro
#If , conditional commands in compilation preprocessing are equivalent to if statements in C syntax
#ifdef determines whether a macro is defined. If so, execute the following statements
#ifndef #ifdef is the opposite of ifdef, which determines whether a macro is undefined
#Elif # if #if, #ifdef, #ifndef or the previous #elif conditions are not met, the statement after #elif is executed, which is equivalent to else if in C syntax
#Else # corresponds to #if, #ifdef, #ifndef. If these conditions are not met, execute the statement after #else, which is equivalent to else in C syntax
#endif #if, #ifdef, #ifndef end flags of these conditional commands
Defined #if and #elif are used together to determine whether a macro is defined

effect:

Using macros can improve the running efficiency of the code: the calling of subroutines needs to be pressed out of the stack, which will cost a lot if it is too frequent

CPU computing resources. Therefore, if some codes with small amount of code but run frequently are implemented by using macros with parameters, the running efficiency of the code will be improved.

Macro definitions are usually divided into object macros and function macros according to whether there are parameters.

Conditional compilation has the following three forms:

#ifdef identifier

          Segment 1

#else

          Segment 2

#endif

Functions of this format: if the identifier has been defined by #define command, compile program segment 1; Otherwise, compile segment 2.

If there is no program 2 (empty), the #else# in this format can be written as:

#ifdef identifier

         Program segment

#endif
#if constant expression
    Segment 1
#else
    Segment 2
#endif

Its function is to compile program segment 1 when the specified expression value is true (non-zero), otherwise compile program segment 2.

Certain conditions can be given in advance to make the program perform different functions under different conditions

Here is an example

#include<stdio.h>

#define BB

#ifdef AA

#define HELLO "hello world"

#elif BB

#define HELLO "hello CC"

#endifint main()

{

printf("%s\n",HELLO);

return 1;

}

error: #if with no expression

reason:

The reason is that although BB is defined, it defines a null value, which cannot be placed #elif later. Because #elif it's not just about checking the macros that follow

If it is defined, its value will be checked. But #ifdef it just checks whether the following macro is defined, regardless of its value.

Try changing #define BB to #define AA, and the result will print hello world.

You can also change #define BB to #define BB # 0. At this time, use GCC - e hello c -o hello. I precompiled can be compiled,

However, the compilation process cannot work because #elif# 0 is false and HELLO is not defined.

Here is another example

//Input a line of alphabetic characters, and set the conditions for compilation as needed, so that it can output all letters in uppercase or all letters in lowercase.
#define LETTER 1
    main()
    {
    char str[20]="C Language",c;
    int i="0";
    while((c=str[i])!='\0'){
    i++;
    #if LETTER
    if(c>='a'&&c<='z') c="c-32";
    #else
    if(c>='A'&&c<='Z') c="c"+32;
    #endif
    printf("%c",c);
    }
    }

The output result is: C LANGUAGE

Now, first define the LETTER as 1, so that when compiling commands under preprocessing conditions, since LETTER is true (non-zero),

The first if statement is compiled and lowercase letters are capitalized at run time.

You can also change the first line of the program to: #define LETTER 0, then compile the second if statement during preprocessing

Process to change the upper case letter into lower case letter (the ASCII code difference between the upper case letter and the corresponding lower case letter is 32).

The output result is: c language

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Tags: C C++

Posted by zszucs on Mon, 25 Apr 2022 20:05:19 +0300