Fundamentals of c language

Environment settings

c program source files usually use the extension. c

c program needs to be compiled into machine language, so that the cpu can execute the program according to the given instructions.

The most commonly used compiler is GCC (xcode on MAC is OK)

Program structure

  • #The include preprocessor instruction, similar to import, is mainly used to tell the compiler what we want to introduce.

  • At the end of. h is the header file, which generally contains defined structures and variables

  • #Include < stdio.h > Import header file, tell the c compiler to import stdio.h file before compiling, and look in / usr/include directory in linux

  • function

  • variable

  • Statement & expression

  • Comments wrapped in /... / are ignored by the compiler

#include <stdio.h>
 
 /*The main function, representing the program, starts here*/
int main()
{
   /* printf Is a function in stdio.h introduced*/
   printf("Hello, World! \n");
   /*Terminate the main function and return 0*/
   return 0;
}

Basic grammar

Semicolon;

';' Semicolon is a statement terminator. Each statement must end with a semicolon, #include and #include do not need to be added;

notes:

Like java

// Single-Line Comments   
/*Multiline
 notes
*/

identifier

The variable name in java is similar to the variable specification in java;

  • C identifier is the name used to identify a variable, function, or any other user-defined item,

  • Identifiers are in letters or underscores_ The beginning can be followed by a number

  • Punctuation such as @, $and% is not allowed in C identifier

  • C is case sensitive. Different cases are two identifiers

keyword

Keywords are reserved and cannot be used as other identifiers such as constant names and variable names

keyword	explain
auto	Declare automatic variables
break	Jump out of current loop
case	Switch statement branch
char	Declare the return value type of a character variable or function
const	Defines a constant if a variable is const Modification, then its value can no longer be changed
continue	End the current cycle and start the next cycle
default	In switch statements"other"branch
do	The body of a loop statement
double	Declares the return value type of a double precision floating-point variable or function
else	Conditional statement negative branch (and if (used together)
enum	Declare enumeration type
extern	Declare that variables or functions are defined in other documents or elsewhere in this document
float	Declares the return value type of a floating-point variable or function
for	A circular statement
goto	Unconditional jump statement
if	Conditional statement
int	Declare an integer variable or function
long	Declare the return value type of a long integer variable or function
register	Declare register variables
return	Subroutine return statement (with or without parameters)
short	Declare a short integer variable or function
signed	Declare a variable or function of signed type
sizeof	Calculate the data type or variable length (i.e. the number of bytes occupied)
static	Declare static variables
struct	Declare structure type
switch	For switch statements
typedef	Used to alias data types
unsigned	Declare an unsigned variable or function
union	Declare common body type
void	The declared function has no return value or parameter, and the declared function has no type pointer
volatile	Description variables can be changed implicitly during program execution
while	Loop condition of loop statement

Basic operation

Similar to java, operators, abbreviations, etc

 a += b; Equivalent to  a = a+b;
 ++  -- and java Similarly, operate before use, and use before operation

Difference: C's remainder operation must be an integer, and java's remainder operation can be a decimal

Escape character

  • \n line feed (also indicates the end of the string)

  • \t horizontal tabulation (equivalent to pressing tab)

  • \b backspace to move the current position to the previous column

  • \f page change, move the current position to the beginning of the next page

  • \r enter

  • \v vertical tabulation

  • ’Single quotation mark

  • Double quotes

  • \Backslash

data type

  • char character type is enclosed by single quotation mark ''

  • Short short shaping

  • int shaping

  • Long long shaping

  • float single precision floating point

  • Double double precision floating point

  • void has no type

  • String types are enclosed in double quotes' '

Basic type and occupancy length

Bytes per base type in 32-bit compiler

Number of bytes per base type in a 64 bit compiler

The number of bytes occupied by each basic type in a 16 bit compiler

typedef unsigned char   uint8_t;     //Unsigned 8-bit 1 byte
typedef signed   char   int8_t;      //Signed 8-bit 1 byte
typedef unsigned int    uint16_t;    //Unsigned 16 bit 2 byte
typedef signed   int    int16_t;     //Signed 16 bit 2 byte
typedef unsigned long   uint32_t;    //Unsigned 32-bit 4-byte
typedef signed   long   int32_t;     //Signed 32-bit 4-byte
typedef float           float32;     //Single precision floating point number 4 bytes
typedef double          float64;     //Double precision floating point number 8 bytes


To get the length of a data type, you can use the sizeof operator

#include <stdio.h>
int main()
{
   short x = 11;
   int y = 4567;
   int short_length = sizeof x;
   int int_length = sizeof(y);
   printf("short length = %d,int length = %d \n",short_length,int_length)
   return 0;
}

Type conversion

Automatic type conversion

Automatic type conversion is the result of automatic judgment by the compiler according to the context of the code. It is silent.

Follow the following rules:

Forced type conversion

(type) variable

double d = 123.8;
//The result of the conversion is saved in the temporary variable x
int x = (int) d

Format controller

Format null character, which indicates the form of output data, starting with%

  • %d outputs an integer, which is short for decimal

  • %hd outputs short int, which is short for short decimal

  • %ld outputs long int, which is short for long decimal

  • %c output a character

  • %s outputs a string

  • %f outputs float type in decimal form

  • %lf outputs the double type in decimal form

  • %e outputs float type in exponential form, and e in the output result is lowercase

  • %E outputs float type in exponential form, and E in the output result is capitalized

  • %le outputs the double type in exponential form, and the e in the output result is lowercase

  • %lE outputs double type in exponential form, and E in the output result is capitalized

  • %g retains up to six significant digits by default, including integer part and decimal part;% f and% e retain six decimal places by default, including only decimal part

  • %X indicates output in hexadecimal

  • %#X means output in hexadecimal with prefix 0X

int x=123;
int a = 'x';
putchar(a) //Dedicated output of characters
printf("%d %c", x,a);


const

const is similar to final in java. After it is defined, its value cannot be changed and remains fixed in the whole scope.

//grammar
const type name = value
//Defines a constant with a maximum age of 150
const int maxAge = 150;
//Re assignment will result in an error
maxAge=88;

const and pointer

//The data pointed to by the pointer is read-only
const int *p1;
int const *p2;


//Read only pointer
int * const p3;

Cycle structure and selection structure

The usage of if else in c language is the same as that in java

The logic operation in c language is the same as that in java

  • &&And operation, corresponding to and in Mathematics

  • ||Or operation, corresponding to or in mathematics

  • ! non operation, corresponding to non operation in mathematics

switch(expression){
    case Integer value 1: Statement 1;
    case Integer value 2: Statement 2;
    ......
    case Integer value n: sentence n;
    default: sentence n+1;
}

For example:
switch(a){
    case 1: printf("Monday\n");
    case 2: printf("Tuesday\n");
    case 3: printf("Wednesday\n");
    case 4: printf("Thursday\n");
    case 5: printf("Friday\n");
    case 6: printf("Saturday\n");
    case 7: printf("Sunday\n");
    default:printf("error\n");
}

Loop in c language is no different from java, and the usage of break and continue is no different

// while loop
#include <stdio.h>
int main(){
    int i, sum=0;
    i = 1;  //Statement ①
    while(i<=100 /*Statement ②*/ ){
        sum+=i;
        i++;  //Statement ③
    }
    printf("%d\n",sum);
    return 0;
}


//for loop

#include <stdio.h>
int main(){
    int i, sum=0;
    for(i=1/*Statement ①*/; i<=100/*Statement ②*/; i++/*Statement ③*/){
        sum+=i;
    }
    printf("%d\n",sum);
    return 0;
}

array

Arrays in c are not very different from java. It should be noted that the types in c are not as strong as java.

Uninitialized values default to the default value of the corresponding type.

//Array initialization
int  arr[3] ={1,2,3}

//Initialization without specifying the length, and directly fill it up
int arr[] = {1,3,4}

  • For short, int and long, it is the integer 0;

  • For char, the character '\ 0';

  • For float and double, it is the decimal 0.0.

character string

There is no concept of string in c. array is used to carry string, and array or pointer is used in c to store string indirectly.

The array used to store characters is called character array. Character array is actually a collection of columns of characters, that is, strings.

c language stipulates that the string can be directly assigned to the character array

char str[10] = {"yxkong"};
char str[10] = "yxkong"; 
char str[] = "yxkong"; //This form is more concise and commonly used in practical development
int len = strlen(str)

  • A string can be assigned at one time only when it is defined

  • Once defined, the assignment can only be modified one character by one character;

  • In c language, strings always end with "\ 0" (\ 0 is the 0th character in ASCII code, also known as Null in English)

  • When processing strings in c, it will scan from front to back one by one. It is found that \ 0 is regarded as the end of the string.

  • The length of the string uses strlen(str)

  • The string can be output in printf() format or directly in puts()

String operation

  • String functions for input and output, such as printf, puts, scanf, gets, etc., should include the header file stdio.h

  • Other string functions include the header file string.h.

String concatenation function strcat()

//Splice y to x
// X must be long enough, or it will cross the boundary (equivalent to adding data to the array of x)
// In the process of splicing, the \ 0 in x will be deleted, and finally the address of x will be returned
strcat(x, y);

String copy function strcpy()

// Copy y to x
// c copies the string from y to x
strcpy(x, y);

String comparison function strcmp()

ASCII values are compared

// x and y are the same and return 0
// X > y returns a value of > 0
// X < y returns a value of < 0
strcmp(x, y);

function

Encapsulate the common code into an independent module in a fixed format. As long as you know the name of this module, you can reuse it. This module is called function.

The functions of C language are called library functions. Libraries developed by other companies or individuals are called third-party libraries

The functions of c language are similar to those of normal java methods (defined first and then used)

c allows you to declare first and then use it. The declaration function can be understood as an interface in java

#include <stdio.h>

//Declare a function add
int add(int x,int y);
int add(int,int); //Same efficiency as above

int main(){
    int rst = add(5,6);
    printf("%d",result);
    return 0;
}
//Declaration function add definition (Implementation)
int add(int x,int y){
    return x+y;
}



c language can directly define code blocks in programs (this is very different from java)

#include <stdio.h>
int main(){
    int x = 20;
    {
        int x = 30;
        //Output 30
        printf("x=%d",x)
    }
    //Output 20
    printf("x=%d",x)
}

Variable scope

The scope of local variables in c is the same as that in java

Global variables are generally defined outside functions. Their default scope is the whole program, that is, all source files, including source file. c and header file. h.

Add static to the variable, and its scope becomes the current file.

It is recommended that all global variables be capitalized to_ separate

#include <stdio.h>
//global variable
int rst =0;
//Current file
int static x=10;
//Declaration function add definition (Implementation)
int add(int x,int y){
    return x+y;
}

int main(){
    int y=6;
    rst = add(x,y);
    printf("%d",result);
    return 0;
}


Preprocessing command

Before c language compilation and linking, it is also necessary to perform some text operations on the source file, such as text replacement, file inclusion, deletion of some code, etc. this process is called preprocessing.

  • Preprocessing commands are commands that begin with #

include command

"#include" is called the file include command. It is used to import the corresponding header file (. h file). It is a kind of preprocessing command

  • #The include command can only contain one header file. Multiple header file references require multiple #include commands

  • Importing the same header file multiple times has the same effect

  • Nesting is allowed for files containing

  • The header file can only contain declarations of variables and functions, not definitions (the definition of the header file is similar to the interface and constant of java)

define command

"#define" is called a macro definition command. Macro definition: an identifier is used to represent a string. If the identifier appears in the following code, it will be replaced with the specified string

  • A macro definition is a string represented by a macro name

  • A macro definition is not a description or statement. You do not need to add a semicolon at the end of the line. If you add a semicolon, it will also be carried when replacing it;

  • The macro definition must be unloaded outside the function. The scope is to the end of the source program, which can be terminated by #undef;

//Macro definition syntax without parameters
#define macro name string

#include <stdio.h>
#define M(3*x+5)
int main(){
    int x = 5;
    int sum = 5*M; //Equivalent to sum = 5*(3*x+5)
    printf("sum = %d",sum)
    return 0;
}

//Macro definition syntax with parameters
#define macro name (parameter list) string

#include <stdio.h>
#define MIN(x,y)  ((x>y)?y:x)

int main(){
    int x = 5,y=8;
    int min = MIN(x,y)
    printf("min = %d",min)
    return 0;
}


Differences between macro definitions with parameters and functions

  • After macro expansion, it is only the replacement of string, and the expression will not be evaluated

  • Macros are replaced before compilation and will not participate in compilation;

  • Function is a piece of reusable code that will be compiled and memory allocated

Conditional compilation

#if integer constant expression 1
    Segment 1
#elif integer constant expression 2
    Segment 2
#elif integer constant expression 3
    Segment 3
#else
    Segment 4
#endif



#ifdef macro name
    Segment 1 (execute if the specified macro name is defined)
#else
    Program segment 2 (if the specified macro name is not defined, this segment is executed)
#endif


#ifndef macro name
    Segment 1 
#else 
    Segment 2 
#endif


Pointer

  • Pointer is used to point to the memory address of bytes in memory

  • Get the memory address of the variable through &

  • If a variable stores a pointer to data, we call it a pointer variable

  • A pointer variable is represented by a * variable name. To define a pointer variable, you must precede the variable*

  • Data in memory (such as arrays) can be obtained through pointer variables

  • The pointer can be directly added with an address. If it is an array, it may be easier to locate

  • If it is a variable, + n indicates the next few bytes of the current address

datatype *name
 Data type pointer name

* Indicates that this is a pointer variable, datatype Indicates the type of data pointed to by the pointer. When defining pointer variables, you must bring*

//Define the int variable a and initialize it to 100
int a = 100;
//Define int pointer p_a and assign the pointer address of a to p_a
int *p_a = &a;

#include <stdio.h>
int main(){
    int a = 22,b=55;
    //The pointer variable ptr points to the address of a
    int *ptr = &a;
    //Get data through pointer variables
    printf("%d",*ptr);
    int c = 15;
    //Modify the address on memory through pointer variables
    *ptr = b;
    //Obtain the data on the memory through the pointer variable (finally, a, B and C are 55)
    c = *ptr
    
    
     printf("%d",*ptr);
     
    //str itself represents the first address of the array and does not need to be added&
    char str[20] = "yxkong";
    printf("%#X, %#X\n", &a, str);
    
   
    return 0;
}

```

about\* and&Question of

```
int  a = 10;
int *pa = &a;

```

*   \*&a Can be understood as \*(&a) ,&a Take the address, \*Take the value of the corresponding address and finally equal to a
    
*   &\*pa Can be understood as&(\*pa) \*pa Got it a Data,&It takes the address and becomes a pointer variable pa
    

### structural morphology

Structure can be understood as java Class in.

*   Definition and use of structure struct
    
*   The structure pointer is also obtained&
    

```
struct Structure name object name;         //"struct structure name" is the data type name of the structure

//Define structure
struct Point{
    int x;
    int y;
};

//When using the newly defined structure Point, you must struct Point and then the object name
struct Point oPoint1={100,100};
struct Point oPoint2;



struct Point{
    int x;
    int y;
} p;

//Structure variable assignment
p.x = 15;
p.y = 22;

//Gets the pointer to the structure
struct Point *ptr = &p;

//Get structure member through structure pointer
(*ptr).x
//Get the member variable of the structure pointer directly through the arrow
*ptr->x


//Structure used only twice
struct {
    int x;
    int y;
} pot1,pot2={34,26};

pot1.x = 11;


```

#### Structure array

```
//It means that there are five students in a class
struct stu{
    char *name;  //full name
    int num;  //Student number
    int age;  //Age
    char group;  //Group 
    float score;  //achievement
}class[5];

//Define the structure array and initialize it
struct stu{
    char *name;  //full name
    int num;  //Student number
    int age;  //Age
    char group;  //Group 
    float score;  //achievement
}class[5] = {
    {"Li ping", 5, 18, 'C', 145.0},
    {"Zhang ping", 4, 19, 'A', 130.5},
    {"He fang", 1, 18, 'A', 148.5},
    {"Cheng ling", 2, 17, 'F', 139.0},
    {"Wang ming", 3, 17, 'B', 144.5}
};

```

#### Using typedef to define a structure

typedef yes c Language that gives a new alias to a data type. It is for coding convenience, similar to syntax sugar. use typedef After, the use of the structure is simplified;

```
//grammar
typedef oldName newName

//This is equivalent to typedef giving struct redisObject an alias robj
typedef struct redisObject{
    ....
} robj;


/**
 * Define a new structure type redisObject
 * Use typedef to alias the structure robj
 * Then you can use robj directly in the program
 */
typedef struct redisObject {
    unsigned type:4;  //Define an unsigned variable type with a length of 4 bits
    unsigned encoding:4;
    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits decreas time). */
    int refcount;
    void *ptr; //Defines a pointer that starts with an * sign
} robj;



robj *createObject(int type, void *ptr) {
    robj *o = zmalloc(sizeof(*o));
    o->type = type;
    o->encoding = OBJ_ENCODING_RAW;
    o->ptr = ptr;
    o->refcount = 1;

    /* Set the LRU to the current lruclock (minutes resolution), or
     * alternatively the LFU counter. */
    if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
        o->lru = (LFUGetTimeInMinutes()<<8) | LFU_INIT_VAL;
    } else {
        o->lru = LRU_CLOCK();
    }
    return o;
}

```

When you need to reference yourself in a structure

```
typedef struct tagNode
{
    char *pItem;
    struct tagNode *pNext;  //Reference your own pointer so that the compiler can recognize it
} *pNode;

```

#### c language enumeration

```
//grammar
enum typeName{ valueName1, valueName2, valueName3, ...... };

//For example, the enumeration value starts from 0 by default, and then increases by 1 one by one
enum week{ Mon, Tues, Wed, Thurs, Fri, Sat, Sun };

//Assign value to enumeration
enum week{ Mon = 1, Tues = 2, Wed = 3, Thurs = 4, Fri = 5, Sat = 6, Sun = 7 };



//Define enumeration variables
enum week a, b, c;

enum week{ Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun } a, b, c;

//Enumeration assignment
enum week a = Mon,b


```

#### Community union

*   A consortium is sometimes called a consortium or a consortium
    
*   Each member of the structure will occupy different memory, and the correlation has no effect
    
*   All members of the community occupy the same memory. Modifying one member will affect all other members
    
*   The memory occupied by the community is equal to the memory occupied by the longest member. The community uses the memory coverage technology, and can only save the value of one member at a time
    
*   Because members are aligned to one end in memory, modifying one member changes the values of other members
    

```
//Define Commons
union data{
    int n;
    char ch;
    double f;
};
//Create variable
union data a, b, c;

//Define and share a body and create variables
union data{
    int n;
    char ch;
    double f;
} a, b, c;


```

![](https://img-blog.csdnimg.cn/img_convert/0b35b60a978c2ed6dd0c1d83951fb833.png)

#### Bit domain

Some data do not need to occupy a complete direct when stored, but only need to occupy one or several binary bits. c Language provides the data structure of bit field.

*   Specifies the number of binary digits occupied by some member variables( Bit)
    
*   By variable name:num To show, num The length of the variable type cannot be exceeded
    
*   The storage rules of bit fields of different compilers are different, but they are trying to compress the storage space as much as possible
    
*   When the types of adjacent members are the same, if the sum of their bit widths is less than the size of the type, the subsequent members are stored next to the previous member until they cannot be accommodated;
    
*   If the sum of their bit widths is greater than the size of the type, the members of the later Europe and America will start from the new storage unit with an offset of an integer multiple of the size of the type;
    
*   When the types of adjacent members are different, different compilers have different implementation schemes, GCC Compressed storage, VC/VS can't
    

```
struct bs{
    unsigned m; //m has no limit and occupies 4 bytes of memory
    unsigned n: 4; //: the following number is used to limit the number of bits occupied by the member variable, occupying 4 bits
    unsigned char ch: 6; //Occupied 6 bits
};

```

Nameless field. Nameless field members have no name and only give the data type and width. They are generally used to fill in or adjust the position of members

```
struct bs{
    int m: 12;
    int  : 20;  //This bit domain member cannot be used
    int n: 4;
};

```



In the above example, if there is no nameless member with a bit width of 20, m,n Will be next to the storage, sizeof(struct bs) The result is 4; with these 20 bits as padding, m,n Store separately, sizeof(struct bs) The result is 8

  

study c,I recommend you to go http://c.biancheng.net

Tags: C

Posted on Tue, 16 Nov 2021 20:20:11 -0500 by crishna369