当前位置:网站首页>Hello C (I) -- basics of C language

Hello C (I) -- basics of C language

2022-06-24 23:41:00 Tianshan old demon

One 、 data type

1、 Basic data type

 

Data types are models that create variables . Variable names are aliases for contiguous storage , Use variables to name storage spaces in programs , Storage space can be used through variables . The amount of memory a variable occupies depends on the data type of the variable created .

2、 Signed and unsigned

The highest bit of a data type in a signed number. A symbol used to identify data , The highest bit is 1 Expressed as a negative number , The highest bit is 0 Expressed as a positive number .

A signed number in a computer is usually represented by a complement , The complement of a positive number is the positive number itself , The complement of a negative number is the inverse of each bit of the absolute value of a negative number and then added 1.

Unsigned numbers in a computer are usually represented by the original code , An unsigned number implies a positive number , There is no sign bit . For unsigned numbers ,MAX_VALUE + 1 be equal to MIN_VALUE,MIN_VALUE - 1 be equal to MAX_VALUE.

When an unsigned number and a signed number are mixed , Will convert signed numbers to unsigned numbers and then calculate , The result is an unsigned number .

Type of integer constant

3、 The implementation of floating point numbers

float And double Data of type is represented in the same way in the computer , Due to different storage space , The numerical range and accuracy that can be expressed are different .

Floating point numbers are stored in three segments in the computer , Sign bit 、 Index 、 mantissa

The conversion of floating-point numbers needs to convert floating-point numbers to binary numbers , The binary floating-point number obtained is represented by scientific counting method , Calculate the index after offset according to the data type . The offset of the index depends on the data type ,float Type plus 127,double Type plus 1023.

8.25 Of float Shown by the following :

8.25 The binary representation of :1000.01==>1.00001(2^3)

Sign bit :0

Index :127+3 = 130 = b10000010

decimal :00001

8.25 Of float Expressed as :0 10000010 00001 000000000000000000 = 0x41040000

because float and int Types take up four bytes ,float The number of specific numbers that can be expressed is the same as int identical , however float The values represented are discontinuous , Cannot be used as an exact number , therefore float The representation range of the type is larger than int The scope of type representation is large .Double The type and float Types are represented the same way in the computer , however double Type takes up a lot of storage space , Therefore, it can be expressed with higher accuracy .

4、 Type conversion

C Data types in language can be converted , Including display type conversion and implicit type conversion .

When casting a type , If the target type can accommodate the target value , The result after conversion will not change ; If the target type cannot hold the target value , The result will result in data truncation .

Implicit type conversions are type conversions performed by the compiler , Implicit conversion from low type to high type is safe , The result is no data truncation ; Implicit conversion from high type to low type is not safe , Results in type truncation , The result may be incorrect .

When implicit type conversions occur :

A、 In arithmetic , Low type to high type

B、 In the assignment expression , The value of an expression is converted to the type of an lvalue

C、 When a function is called , The argument is converted to the type of the formal parameter

D、 When function returns ,return Expression converted to return value type

5、void type

void Modify function return values and parameters

void Cannot be used to define variables , standard C In the language compiler sizeof(void) Will report a mistake ,GCC Because of the extension in the compiler , No mistake. , The result is 1.

Two 、 Program structure

1、 Branch statement

if...else

if Statement select the execution statement according to the condition ,else Can't exist independently , But always with the nearest if matching .

float Variables cannot be directly combined with 0 Compare , It is necessary to make sure that the variable is in a small interval .

if(-0.0000001 < a && a < 0.0000001)

switch

switch Statement corresponds to multiple values of a single condition , In general case The statement needs to have break, Otherwise, the branches will overlap .default Branches need to be added , Used to deal with special situations .

case A value in a statement can only be an integer or char type .

2、 Loop statement

do Statements are executed first and then judged , The loop body performs at least once

do

{

}while();

while The statement is judged before execution , The loop body may not execute

while()

{

}

for The statement is judged before execution

for(; ; )

break Indicates that the execution of the loop is terminated

continue It means to stop this cycle , Enter next cycle

3、 ... and 、const and volatile

1、const

const Decorated variables tell compile time that variables are read-only , But it's still a variable , Indicates to the compiler that a variable cannot be an lvalue .

const Decorated local variables allocate space on the stack

const Decorated global variables allocate space in the global data area

const Valid only at compile time , Invalid during runtime

#include <stdio.h>
const int g = 10;

int main(int argc, char **argv)
{
    const int c = 1;
    int *p = (int *)&c;
    *p = 100;
    printf("%d\n", c);
    p = (int *)&g;
    *p = 1000;
    printf("%d\n", c);

    return 0;
}

Compilation of normal , Using a pointer at runtime allows you to const Modify local variables , But use a pointer to const A segment error occurred while modifying a global variable .

standard C The language compiler will not const Decorated global variables are stored in a read-only storage area , It is stored in a global data area that can be modified , Its value can be modified by pointer . But modern compilers like GCC take const Global variables are stored in read-only storage , Modifying its value through a pointer will cause a segment error .const volatile Decoration can store global variables in the global data area , Its value can be modified .

const Modifying a function parameter means that you do not want to modify the value of the parameter inside the function body

const The return value of the modifier function indicates that the return value cannot be changed

#include <stdio.h>

const volatile int g = 10;

int main(int argc, char *argv[])
{
    const int i = 0;
    int *p = (int *)&i;
    *p = 100;
    printf("%d %d\n", i, *p);
    p = (int *)&g;
    *p = 1000;
    printf("%d %d\n", g, *p);

    return 0;
}

2、volatile

volatile Indicates that the compiler cannot optimize , You must fetch the value of a variable from memory each time , It mainly modifies variables accessed by multiple threads 、 Or variables that have been changed for unknown reasons

const volatile int i = 10;

As a local variable ,i You can't do lvalue , But you can use a pointer to change the value , The compiler does not support variables i To optimize , Each time, the value is fetched from the memory .

Four 、struct and union

1、struct

A flexible array is an array whose size is undetermined

The last member in the structure can be a flexible array , A flexible array is just an identifier , No storage space .

2、union

union Allocate only the space of the largest member , All members share this space .

union The use of will be affected by the size of the computer

Use union The code for testing the size side of the computer is as follows :

#include <stdio.h>

void big_little(void);

int main(int argc, char *argv[])
{
    big_little();

    return 0;
}

void big_little(void)
{
    union Mode
    {   
        char c;
        int i;
    };  
    union Mode m;
    m.i = 1;
    if(m.c)
    {   
        printf("little\n");
    }   
    else
    {   
        printf("big\n");
    }   
}

5、 ... and 、enum、sizeof、typedef

1、enum

enum yes C A custom type in a language ,enum The value of is a custom integer value , First defined enum The value is defaults to 0, By default enum The value of is the value of the previous definition plus 1, You can also specify .enum The value defined in is C Real constants in languages

2、sizeof

sizeof Is the built-in indicator of the compiler , Used to calculate the memory occupied by the type or variable ,sizeof The value of is determined at compile time .

int var = 0;

int size = sizeof(var++);

var They don't execute var++, Instead, at compile time sizeof(var++ Replace with value 4

3、typedef

typedef Used to rename an existing type , In essence, it does not produce new types

typedef The renamed source type can be found in typedef Definition after statement ,typedef Out of commission unsigned、signed modification .

6、 ... and 、 Connector 、 Single quotation marks 、 Double quotes

1、 Connector

C Connectors in languages (\) You can instruct the compiler , The compiler will delete the connector , The character following the continuation character is automatically continued to the previous line . When connecting words , There must be no space after the continuation character , There should also be no spaces before the next line of the continuation . Usually, the continuation is used when defining a macro code block .

2、 Single and double quotes

C In languages, single quotation marks are used to denote character literals , Double quotation marks are used to indicate string literals

‘a’ Represents the literal amount of a character , Take a byte of size ,’a’+1 Express ’b’,”a” Represents the literal amount of a string ,”a”+1 Indicates pointer operation , The result points to ”a” End of string ’\0’.

char c = “hello”;

Literal of a string “hello” The address of is assigned to the character variable c, Because the address takes up four bytes , Type truncation occurs when a character type is assigned .

7、 ... and 、++、--、 Ternary operator

1、++、--

++、-- The result of participating in the hybrid operation is uncertain .

2、 Ternary operator

The ternary operator returns the value of a variable , Not the variables themselves . Determine the return value type according to the implicit type conversion rules .

int a = 1;
int b = 2;
int c = 0;
c = a < b ? a : b;
(a < b ? a : b) = 3;//error
*(a < b ? &a : &b) = 3;//ok

8、 ... and 、 macro

1、 Macro definition

#define Processed by a preprocessor , Direct text replacement , No syntax checking ,#define Defined macros can appear anywhere in the program

#define Macro constants defined are literal in nature

Macros are processed by the preprocessor , The compiler does not know the existence of macros .

Macro expressions don't have any call overhead , Recursive definitions cannot appear

Compiler built-in macros :

__FILE__: The name of the compiled file

__LINE__: The current line number

__DATE__: Compile time date

__TIME__: Compile time

__STDC__: Whether the compiler complies with the standard C standard

#define LOG(s) printf("[%s] File:%s, Line:%d %s \n", __DATE__, __FILE__, __LINE__, s)

2、 Conditional compilation

Conditional compilation is a precompiled instruction command , Used to control whether to compile a piece of code . The precompiler selectively deletes code according to conditional compilation instructions , The compiler does not know the existence of code branches .

Conditional compilation can solve the compilation errors contained in the header file repeatedly

#ifndef _FILE_H_
#define _FILE_H_

//source code

#endif

Conditional compilation compiles different code through different conditions , Generate targets with different conditions , In actual projects, conditional compilation can be used to generate different product lines from the same project code, or to distinguish the debugging and release versions of products .

3、#error

#error Used to generate a compilation error message

grammar :#error message

message You don't need double quotes

#ifndef __cplusplus__
    #error This file should be processed with C++ compiler.
#endif

An error message generated during compilation means that compilation will be terminated , Unable to generate final executable

4、#line

#line Used to force new line numbers and compiled file names to be specified , And renumber the source code

#line number filename

#line In essence, it is right to __LINE__ and __FILE__ Redefinition of macros

5、#pragma

#pragma Used to instruct the compiler to complete certain actions , Many of the keywords defined are related to the compiler , It is not portable between different compilers . The preprocessor will ignore unknown #pragma Instructions , Different compilers may be able to #pragma Instructions are interpreted differently .

#pragma message

Compile time output messages to the compiler output window , Used to prompt information

#if defined(ANDROID20)
    #pragma message("Compile Android SDK 2.0...")
    #define VERSION "Android 2.0"
#elif defined(ANDROID23)
    #pragma message("Compile Android SDK 2.3...")
    #define VERSION "Android 2.3"
#elif defined(ANDROID40)
    #pragma message("Compile Android SDK 4.0...")
    #define VERSION "Android 4.0"
#else
    #error Compile Version is not provided!
#endif

And #error Different ,#pragma massage Represents only one compilation message , It does not mean that there is a compilation error

#pragma once

#pragma once Used to ensure that the header file is compiled only once , Compiler related , The compiler does not necessarily support .

The engineering code is used as follows :

#ifndef _FILE_H_
#define _FILE_H_

#pragma once



#endif

#pragma pack

#pragma pack Used to specify memory alignment , Usually used in pairs

#pragma pack(n)

//source code

#pragma pack()

6、# Operator

# Operator is used to convert macro parameters to strings during preprocessing , Only valid in macro definitions

#define STRING(x) #x

printf("%s\n", STRING(Hello world!));

#define CALL(f, p) (printf("Call function %s\n", #f), f(p))

7、## Operator

## Operator is used to glue two identifiers during preprocessing , Valid only in macro definitions

#define NAME(n) name##n

int main()
{
    int NAME(1);
    int NAME(2);
    NAME(1) = 1;
    NAME(2) = 2;
    printf("%d\n", NAME(1));
    printf("%d\n", NAME(2));

    return 0;
}

Nine 、main function

main Function is a function called by the operating system , The operating system will main Function as the entry to the application , take main The return value of the function is used as the exit state of the program .

Modern compilers support main Call other functions before function .

#include <stdio.h>

#ifndef __GNUC__
#define __attribute__(x)
#endif

__attribute__((constructor))
void before_main()
{
    printf("%s\n",__FUNCTION__);
}

__attribute__((destructor))
void after_main()
{
    printf("%s\n",__FUNCTION__);
}

int main()
{
    printf("%s\n",__FUNCTION__);

    return 0;
}

Ten 、 Program memory layout

Correspondence between different codes in executable programs :

The stack does not officially exist until the program is running , It is the basis of program operation .

.bss Section stores uninitialized global variables and static variables

.text Section stores the executable code of the program

.data Segment stores initialized global variables and static variables

.rodata Segment stores constant values in the program , Such as the literal character of the string

Static storage area usually refers to .data Paragraph and .bss paragraph

A read-only storage area usually refers to .rodata paragraph

Code snippets usually refer to .text paragraph

原网站

版权声明
本文为[Tianshan old demon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211118041491.html