Teach you simple programming in C language

Time:2021-12-2

We put all the C language elements on an easy to read memo.

Teach you simple programming in C language

Dennis Ritchie worked at Bell Labs in 1972. A few years ago, he and his team members invented UNIX. After creating an enduring operating system (still in use today), he needed a good way to program these UNIX computers so that they could perform new tasks. It seems strange now, but at that time, there were relatively few programming languages. FORTRAN, lisp, ALGOL and B languages were very popular, but they were far from enough for what Bell Labs researchers wanted to do. Dennis Ritchie showed a major characteristic later known as programmer: he created his own solution. He called it c language, and nearly 50 years later, it is still widely used.

Why should you learn C language

Today, there are many languages that provide programmers with more features than C. The most obvious is the C + + language, which is named in a very explicit way. It is built on the C language and creates a good object-oriented language. However, many other languages exist for good reasons. Computers are good at consistent repetition, so anything predictable can be built in a programming language, which means less work for programmers. Why use two lines of statements in C + + language when you can convert an int to a long (long x = long (n);) with one line of statements?

However, C language is still useful today.

First of all, C language is quite simple and direct. In addition to the basic knowledge of programming, there is no high-level concept, which is largely because C language is actually one of the foundations of modern programming language. For example, one of the features of C language is array, but it does not provide a dictionary (unless you write one yourself). When you learn C language, you will learn the basic components of programming, which can help you realize the improvement of today’s programming language and its careful design.

Teach you simple programming in C language

Because C is a minimal programming language, your application is likely to improve performance, which is not seen in many other programming languages. When you think about how fast your code can execute, it’s easy to get into a situation of penny pinching. Therefore, it’s important to ask whether you canneedProvide more speed for a specific task. Compared with Python or Java, using C language, you need less entanglement in each line of code. C language program runs very fast. This is a good reason why the Linux kernel is written in C language.

Finally, C language is easy to get started, especially if you are running Linux, you can already run C language code, because the Linux system includes GNU C library (glibc). In order to write and build C language programs, all you need to do is install a compiler, open a text editor and start coding.

 

Start learning C language

If you are running Linux, you can use your package manager to install a C compiler. On Fedora or RHEL:

$ sudo dnf install gcc

On Debian and its derivatives:

$ sudo apt install build-essential

On MacOS, you can install homebrew and use it to install GCC:

$ brew install gcc

On windows, you can use MinGW to install a minimal set of GNU utilities containing GCC.

Verify that you have installed GCC on Linux or MacOS:

$ gcc --version
gcc (GCC) x.y.z
Copyright (C) 20XX Free Software Foundation, Inc.

On windows, provide the full path of the EXE file:

PS> C:\MinGW\bin\gcc.exe --version
gcc.exe (MinGW.org GCC Build-2) x.y.z
Copyright (C) 20XX Free Software Foundation, Inc.

C grammar

C is not a scripting language. It is a compiled language, which means that it is processed by the C compiler to produce a binary executable. This is different from scripting languages such as bash or mixed languages such as python.

In C language, you can createfunctionTo do what you want. By default, a function named main is executed.

Here is a simple “Hello world” program written in C language:

#include 

int main() {
  printf("Hello world");
  return 0;
}

The first line contains a file called stdio. H (standard input and output)Header file, it is basically free-use, very elementary C language code, and you can reuse it in your own programs. Then you create a function called main that consists of a basic output statement. Save the text to a file called hello. C, and then compile it using gcc:

$ gcc hello.c --output hello

Try running your C program:

$ ./hello
Hello world$

Return value

This is part of UNIX philosophy. A function “returns” something after execution: nothing on success and something else on failure (for example, an error message). These returned contents are usually represented by numbers (to be exact, integers): 0 indicates no error, and any number greater than 0 indicates some unsuccessful status.

UNIX and Linux are designed to be silent when running successfully. This is so that when you execute a series of commands, assuming that no errors or warnings will hinder your work, you can always prepare for successful execution. Similarly, functions in C are designed without errors.

You can make your program look failed through a small modification. You can see this:

include 

int main() {
  printf("Hello world");
  return 1;
}

Compile it:

$ gcc hello.c --output failer

Now run it using a built-in linux test mode. Only insuccessThe & & operator executes the second part of a command. For example:

$ echo "success" && echo "it worked"
success
it worked

stayfailThe test executes the second part of a command.

$ ls blah || echo "it did not work"
ls: cannot access 'blah': No such file or directory
it did not work

Now, try your program and, when successful, itnoReturn 0; Instead, return 1:

$ ./failer && echo "it worked"
String is: hello

The program executed successfully, but did not trigger the second command.

Teach you simple programming in C language

Variables and types

In some languages, you can create variables without specifying the data contained in the variablestype。 These languages are so designed that the interpreter needs to run some tests on a variable to find out what data type the variable is. For example, VAR = 1 defines an integer. When you create an expression to add VaR to something, python knows that it is obviously an integer. It also knows that when you connect hello and world, the word world is a string.

C language will not do any identification and investigation for you; You must define your own variable type. There are several variable types, including integer (int), character (char), floating point (float), Boolean (Boolean).

You may also notice that there is no string type here. Unlike python, Java, Lua and other programming languages, C language does not have string types, but regards strings as an array of characters.

Here are some simple codes. It creates a char array variable, and then uses printf to print the array variable and a simple piece of information to your screen:

#include 

int main() {
   char var[6] = "hello";
   printf("Your string is: %s\r\n",var);
}

You may notice that this code example provides six character space for a five letter word. This is because there is a hidden terminator at the end of the string, which takes up a byte in the array. You can run it by compiling and executing code:

$ gcc hello.c --output hello
$ ./hello
hello

function

Like other programming languages, C functions accept optional parameters. You can pass parameters from one function to another by defining the data type you want the function to accept:

#include 

int printmsg(char a[]) {
   printf("String is: %s\r\n",a);
}

int main() {
   char a[6] = "hello";
   printmsg(a);
   return 0;
}

This method of simply decomposing a function into two functions is not very useful, but it demonstrates how to run the main function by default and how to pass data between functions.

Teach you simple programming in C language

Conditional statement

In real programming, you usually want your code to make judgments based on data. This is usedconditionThe if statement is the most basic one.

To make the sample program more dynamic, you can include a string. H header file, which, as the name suggests, contains code for checking strings. Try using the strlen function from the string. H file to test whether the string passed to the printmsg function is greater than 0:

#include 
#include 

int printmsg(char a[]) {
  size_t len = strlen(a);
  if ( len > 0) {
    printf("String is: %s\r\n",a);
  }
}

int main() {
   char a[6] = "hello";
   printmsg(a);
   return 1;
}

As implemented in this example, this condition will never be untrue because the supplied string is always hello and its length is always greater than 0. The last thing to do with this poorly re implemented echo command is to accept input from the user.

Command parameters

The code contained in stdio. H file provides two parameters each time the program starts: one is the count of how many items are contained in the command (argc), and the other is the array containing each item (argv). For example, suppose you issue this fictional command:

$ foo -i bar

Argc is 3, and the contents of argv are:

  • argv[0] = foo
  • argv[1] = -i
  • argv[2] = bar

Can you modify the sample C language program to accept argv [2] as a string instead of the default hello?

Imperative programming language

C language is an imperative programming language. It is not object-oriented and has no class structure. The experience of using C language can teach you a lot about how to deal with data and how to better manage the data generated by your code runtime. By using more C language, you can finally write libraries that can be used by other languages (such as Python and Lua).

To learn more about C, you need to use it. Look for useful C header files in / usr / include / and see what small tasks you can do to make C useful to you. In the process of learning, use the C language memo written by Jim Hall from FreeDOS. It places all the basic elements on a double-sided memo, so you can immediately access all the elements of C language grammar when you practice.

Author: Linux China
Source: Nuggets