C language learning - initial C language (2)

function

The basic unit that constitutes a C program is a function, which contains the executable code of the program. All simple programs can define other additional functions. When writing a program, not all content is placed in the main function main. In order to facilitate planning, organization, writing and debugging, the general method is to divide a program into several Each program module can complete a function. In this way, different module programs can be completed by different people, so that the efficiency of software development can be improved.

  • The main function can call other functions;
  • Other functions can also call each other.

The definition form of the function:
返回类型 函数名称(参数){函数体(实现函数的功能)}
Return type: It is the data type of the return value of the function. Some functions do not need to return a value. The return type of this function is void.
Function name: It is the actual name of the function, and it is called with the function name when calling.
Parameters: are like placeholders. When the function is called, you pass a value to the parameter, which is called the actual parameter. The parameter list includes the type, order, and number of function parameters. Parameters are optional, that is, functions may contain no parameters.
Function body: It is a block of code that performs a specific task.

int add(int a,intb) //函数头部
{
    
    
    int c=a+b;//实现特定任务
    return c;//返回一个值
}

Here is the code for the function call:

int Add(int a, int b)
{
    
    
	int c = a + b;
	return c;
}

int main()
{
    
    
	int a = 5;
	int b = 5;
	int count = Add(a, b);
	printf("%d", count);
	return 0;
}

Note:
User-defined functions cannot be written after the main function (main function), which will cause program errors.

array

  • The declaration of an array is not a declaration of variables one by one, but a collection.
  • All arrays consist of contiguous memory locations. The lowest address corresponds to the first element, and the highest address corresponds to the last element. As shown below:

Array screenshot.png

array definition

类型说明符 数组标识符【常量表达式】

  • Type specifier: Indicates the type of all elements in the array.
  • Array identifier: indicates the name of the array type variable, and the naming rules are the same as the variable name.
  • Constant expression: defines the number of data elements stored in the array, that is, the length of the array.

For example, define an array as follows:
int arr[10]={0,1,2,3,4,5,6,7,8,9};

array subscript

The C language stipulates that each element of the array has a subscript, and the subscript starts from 0.
Arrays can be accessed by subscripting.
int arr[10]={0,1,2,3,4,5,6,7,8,9};

Only subscript [0~9] can be used in the array arr[10], because the array subscript starts from 0.

array usage

If you want to print the elements of 1~10! If you don't use an array, you need to create 10 variables for storage, which will be troublesome.
Then we can store it well when we use an array, because an array is a set of identical elements. As shown below:

#include<stdio.h>
int main()
{
    
    
	int i = 0;
	int arr[10] = {
    
     1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ",arr[i]);
	}
	return 0;
}

operator

C language provides a very rich set of operators, including the following operators.

arithmetic operator

+ - * / %
Addition, subtraction, and multiplication are the same as what I learned in previous mathematics. The focus is on division (/) and modulo (%)
division (/):
divided into integer division and floating-point division.
The integer time quotient obtained in integer division, I don’t care about the remainder. As shown in the figure below, the result of int 9/2 is 4.
Division.png
Why didn’t I get 4.5? Because when both ends of the division sign are integers, integer division is performed. If one of the two ends is a floating point number Just perform floating-point division.
Next, I will change one side to a floating-point number and the result is shown in the figure below:
Floating-point division.png
Modulo (%):
the result is the remainder, and only integers can be manipulated

shift operator

<< >>
Move left and move right

The shift operator involves binary, which will be explained in detail in a later blog.

bitwise operator

& ^ |
bitwise and bitwise or bitwise exclusive or

This will also be explained in detail in the following blogs. Here is just an explanation of the initial C language.

assignment operator

= += -= *= /= &= ^= |= >>= <<=
Assignment, addition, subtraction, multiplication, division, etc. bitwise AND, etc. bitwise OR, etc. bitwise XOR, etc. Right shift, etc. Left shift, etc.

Among the assignment operators, the ones we use the most are the top 5 operators. We can understand "addition and so on" in this way

int a,b;
a=a+b;
//或者这样写
a+=b;

Including subtraction, multiplication, division, etc., and the use of addition, etc. is the same. As for the remaining assignment operators, I will introduce them one by one in detail in the following blog.

unary operator

When are unary operators? An operator with only one operand.

! logical inversion
- negative value
+ positive value
& take address
sizeof the type length of the operand in bytes
~ Bitwise inverse of a number
front, rear –
++ Front, rear++
* dereference operator
(type) cast

Below I briefly introduce a few operators, as for the remaining operators, I will introduce them in detail in the following blog.
In the C language, it is stipulated that non-zero is true and 0 is false. Then it can be understood that -1 is true. The following code:

int main()
{
    
    
	int a = 0;
	if (!a)//a等于0时为假,!a为真
	{
    
    
		printf("hello");
	}
    return 0;
}

The output result is:

hello

This is a brief introduction to the "!" unary operator. Here is an operator that is often misunderstood: sizeof()
sizeof is an operator, not a function.

int main()
{
    
    
	int a = 0;
	printf("%d", sizeof(a));//计算a所占空间的大小
	printf("%d", sizeof(int));//也可以换成类型
	printf("%d", sizeof a);//因为sizeof不是一个函数,可以去掉(),
	//这一点进一步证明sizeof是操作符不是函数  但sizeof int 这样是不行的。
	return 0;
}

Let's introduce another pre-, post-++ or –
Rear++.png
Front++.png
from this it can be concluded:

  • Prepending ++ or – first auto-increment and then assignment
  • Postfix ++ or – first assign and then increment

As for the remaining unary operators, I will introduce them in detail in future blogs.

relational operator

> more than the
>= greater or equal to
< less than
<= less than or equal to
!= not equal
== equal
int main()
{
    
    
	int a = 10;
	if (a=3)
	{
    
    
		printf("hello");
	}
	return 0;
}

"hello" will be printed here, but it is assigned here, not judging that it needs to be changed toa==3

int main()
{
    
    
	int a = 10;
	if (a==3)//判断a是否等于3
	{
    
    
		printf("hello");
	}
	return 0;
}

logical operator

&& logic and
|| logical or
  • && is true if both are true, and if one of them is false, then all are false.
  • || is true as long as one of the results is true.

conditional operator

exp1?exp2:exp3

The conditional operator can also be called a ternary operator, expression 1 is true, expression 2 is counted, expression 3 is not counted (the expression result is the result of expression 2); expression 1 is false, expression 2 is not counted , expression 3 counts (the expression result is the result of expression 3).

comma expression

exp1, exp2, exp3, …expN

Comma expressions are evaluated from left to right, and the result of the comma expression is the result of the last expression.
comma-expression.png

Subscript references, function calls, and structure members

[ ] () . ->

Here I introduce the first two

void Print(int arr[], int b)
{
    
    
	for (int i = 0; i < b; i++)
	{
    
    
		printf("%d\t", arr[i]);
	}
}
int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9 };
	arr[4] = 20;//这里的[]操作符就是下标引用操作符  arr和4就是[]的操作数
	printf("%d\n", arr[4]);
	Print(arr, 9);//()就是函数调用操作符,Print,arr,9都是()的操作数
	return 0;
}

I will introduce the remaining operators in detail later.

common keywords

auto break case char const continue default do double else enum
extern float for goto if int long register return short signed
sizeof static struct switch typedef union unsigned void volatile while

The C language provides abundant keywords, and users cannot create keywords by themselves.

Keyword classification

  1. Data type keywords (12)
char Declare a character variable or function
double Declare a double precision variable or function
enum Declaring an enumeration type
float Declare a floating-point variable or function
int Declare an integer variable or function
long Declare a long variable or function
short Declare a variable or function of type short
signed Declare a variable or function of signed type
struct Declare a structure variable or function
union declare union type
usigned Declare a variable or function of unsigned type
void Declare functions with no return type or parameters, declare untyped pointers
  1. Control statement keywords (12)
for loop statement
do The body of the loop statement
while Loop condition for loop statement
break break out of the current loop
continue End the current cycle and enter the next cycle
if Conditional statements
else conditional statement negates branch
goto unconditional jump statement
switch user switch statement
case switch statement branch
default Other branches in the switch statement
return return
  1. Storage type keywords (4)
auto Declare automatic variables
extern Variables are declared in other files
register Declare register variables
static declare static variable
  1. Other keywords (4)
const Declare a read-only constant
sizeof Calculate data type length
typedef Use a data type to alias
volatile Indicates that variables can be implicitly changed during program execution

typedef keyword

在C语言中有一个typedef关键字,其用来定义用户自定义类型。当然,并不是真的创造了一种数据类型,而是给已有的或者符合型的以及复杂的数据类型取一个我们自己更容易理解的别名。总之,可以使用typedef关键字定义一个我们自己的类型名称。例如:

//将unsigned int 重命名为uint, 所以uint也是一个类型名
typedef unsigned int uint;
int main()
{
    
    
    //观察num1和num2,这两个变量的类型是一样的
    unsigned int num1 = 0;
    uint num2 = 0;
    return 0;
}

static关键字

在C语言中:
static是用来修饰变量和函数的

  1. 修饰局部变量-称为静态局部变量
  2. 修饰全局变量-称为静态全局变量
  3. 修饰函数-称为静态函数

修饰局部变量

#include <stdio.h>
void test()
{
    
    
    //static修饰局部变量
    static int i = 0;
    i++;
    printf("%d ", i);
}
int main()
{
    
    
    int i = 0;
    for(i=0; i<10; i++)
   {
    
    
        test();
   }
    return 0;
}

结论:

  • static修饰的变量改变了变量的生命周期
  • 让静态变量出了作用域还存在,直到程序结束变量的生命周期才结束。

修饰全局变量

//代码1
//add.c
int g_val = 2018;
//test.c
int main()
{
    
    
    printf("%d\n", g_val);
    return 0;
}
//代码2
//add.c
static int g_val = 2018;
//test.c
int main()
{
    
    
    printf("%d\n", g_val);
    return 0;
}

结论:

  • 一个全局变量被static修饰,使得这个全局变量只能在本源文件内使用,不能在其他源文件内使

用。

修饰函数

修饰函数和修饰全局变量一样的呢,都只能在本源文件内使用了。

define定义常量和宏

//define定义标识符常量
#define MAX 1000
//define定义宏
#define ADD(x, y) ((x)+(y))
#include <stdio.h>
int main()
{
    
    
    int sum = ADD(2, 3);
    printf("sum = %d\n", sum);
    
    sum = 10*ADD(2, 3);
    printf("sum = %d\n", sum);
    
    return 0;
}

指针

指针是c语言中的一个重要概念,也是C语言的一个重要的特色,正确而灵活地运用它,可以使程序简洁,紧凑,高效,每一个学习和使用c语言的人,都应当深入了解地学习和掌握指针,可以说,不掌握指针就是没有掌握C的精华也可以说指针是C语言的灵魂。

内存

  • 内存是电脑上特别重要的存储器,计算机中程序的运行都是在内存中进行的 。
  • 所以为了有效的使用内存,就把内存划分成一个个小的内存单元,每个内存单元的大小是1个字节
  • 为了有效的访问到内存的每个单元,就给内存单元进行了编号,这些编号被称为该内存单元的地址。

每个变量都是创建在内存中的,即每个内存单元都有地址,所以变量也是有地址的。

#include <stdio.h>
int main()
{
    
    
 int num = 20;
 &num;//取出num的地址
    //注:这里num的4个字节,每个字节都有地址,取出的是第一个字节的地址(较小的地址)
 printf("%p\n", &num);//打印地址,%p是以地址的形式打印
 return 0;
}

如何存储地址呢?这就需要用到指针变量。

int mun=20;
int *p;//p为整型指针
p=&num;

怎么使用指针呢?如下所示:

#include<stdio.h>
int main()
{
    
    
    int mun=20;
    int *p=&num;
    *P=30;
    printf("%d",mun);
    return 0;
}

其他类型使用方法也是一样的。

指针变量的大小

#include <stdio.h>
//指针变量的大小取决于地址的大小
//32位平台下地址是32个bit位(即4个字节)
//64位平台下地址是64个bit位(即8个字节)
int main()
{
    
    
    printf("%d\n", sizeof(char *));
    printf("%d\n", sizeof(short *));
    printf("%d\n", sizeof(int *));
    printf("%d\n", sizeof(double *));
    return 0;
}

指针的大小在32位平台上是4个字节,在64位平台上是8个字节。

结构体

A structure is a collection, which contains multiple variables or arrays, and their types can be the same or different, and each such variable or array is called a member of the structure. Members of structures can be scalars, arrays, pointers, or even other structures.

struct 结构名
{
    
    
类型 变量名;
类型 变量名;
...
} 结构变量;

Example:

struct Stu
{
    
    
    char name[20];//名字
    int age;      //年龄
    char sex[5];  //性别
    char id[15]//学号
};

Initialize the structure:

//打印结构体信息
struct Stu s = {
    
    "张三"20"男""20180101"};
//.为结构成员访问操作符
printf("name = %s age = %d sex = %s id = %s\n", s.name, s.age, s.sex, s.id);
//->操作符
struct Stu *ps = &s;
printf("name = %s age = %d sex = %s id = %s\n", ps->name, ps->age, ps->sex, ps-
>id);

The above introduces functions, arrays, operators, keywords, pointers and structures. There are still many contents that have not been introduced. Each content will be introduced in a separate blog. Here are mainly the things in the initial C language. The next blog will cover branching and looping statements in detail. Looking forward to our next meeting, bye. Don't forget to follow me and learn C language with me.

Guess you like

Origin blog.csdn.net/weixin_63284756/article/details/130161333
Recommended