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

In 1972, Dennis Ritchie worked for Bell Labs. A few years earlier, he and his team had invented Unix. Having created an enduring operating system that is still in use today, he needed a good way to program these Unix computers so that they could perform new tasks. It may seem strange now, but at the time there were relatively few programming languages. Fortran, Lisp, Algol, and B were all popular, but they were far from enough for what the Bell LABS researchers wanted to do. Dennis Ritchie exhibited what came to be known as the defining characteristic of programmers: he created his own solutions. He called it C, and nearly 50 years later, it’s still widely used.

Why should you learn C

Today, there are many languages that offer programmers more features than C. The most obvious is C++, a language named in a rather blatant way that builds on C to create a nice object-oriented language. However, many other languages exist for good reason. Computers excel at consistent repetition, so anything predictable can be built into programming languages, which means less work for programmers. Why is it possible to convert an int to a long with a single line in C++ (long x = long(n);)? And two lines in C?

However, C is still useful today.

First, C is a fairly minimalist and straightforward language. Beyond the basics of programming, there are no very advanced concepts, largely because C is actually one of the foundations of modern programming languages. For example, one of the features of C is arrays, but it doesn’t provide dictionaries (unless you write one yourself). When you learn C, you learn the basic building blocks of programming, which can help you realize the improvements and careful design of today’s programming languages.

Because C is a minimal programming language, your application is likely to get a performance boost that you don’t see in many other programming languages. When you think about how fast your code can execute, it’s easy to get caught up in being cheap, so it’s important to ask if you need more speed for a particular task. With C, you have fewer tangled areas per line of code than with Python or Java. C programs run fast. This is a good reason for the Linux kernel to be written in C.

Finally, C is easy to get started with, especially if you’re running Linux, which includes the GNU C library (Glibc). To write and build C programs, all you need to do is install a compiler, open a text editor, and start coding.

Start learning C

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

$ sudo dnf install gcc
Copy the code

On Debian and its derivatives:

$ sudo apt install build-essential
Copy the code

On macOS, you can install Homebrew and use it to install GCC:

$ brew install gcc
Copy the code

On Windows, you can install a minimal set of GNU utilities including GCC using MinGW.

Verify that you have GCC installed on Linux or macOS:

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

On Windows, provide the full path to 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.
Copy the code

C syntax

C is not a scripting language. It is a compiled language, meaning that it is processed by the C compiler to produce a binary executable. This is different from scripting languages (like Bash) or hybrid languages (like Python).

In C, you can create functions to do whatever you want. By default, a function called main is executed.

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

#include <stdio.h>

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

The first line contains a header called stdio.h (standard input and output), which is basically free-use, very rudimentary C code that you can reuse in your own programs. Then you create a function called main consisting of a basic output statement. Save the text to a file called hello.c, and compile it using GCC:

$ gcc hello.c --output hello
Copy the code

Try running your C program:

$ ./hello
Hello world$
Copy the code

The return value

It is part of the Unix philosophy that a function “returns” something after execution: nothing on success and something else on failure (for example, an error message). These returns are usually represented as numbers (integers, to be exact) : 0 means no errors, and any number greater than 0 means some unsuccessful state.

Unix and Linux are wisely designed to remain silent when running successfully. This allows you to execute a series of commands assuming that no errors or warnings will interfere with your work, so that you can always prepare for successful execution. Similarly, functions in C are designed to be error-free.

You can see this with a small change that makes your program look like a failure:

include <stdio.h>

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

Compile it:

$ gcc hello.c --output failer
Copy the code

Now run it using a built-in Linux test. The && operator executes the second part of a command only if it succeeds. Such as:

$ echo "success" && echo "it worked"
success
it worked
Copy the code

When the failure, | | the second part of the test will execute a command.

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

Now, try your program. On success, it does not return 0; Instead, return 1:

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

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

Variables and types

In some languages, you can create variables without specifying the type of data that the variable contains. These languages are designed in such a way that the interpreter needs to run tests on a variable to see what data type the variable is. For example, var=1 defines an integer, and when you create an expression to add var to something, Python knows that it is clearly an integer. It also knows that when you concatenate hello and world, the word world is a string.

C doesn’t do any of this identification and investigation for you; You must define your own variable types. There are several variable types, including integer (int), char (char), float, and Boolean.

You may also notice that there is no string type here. Unlike Python and Java and Lua and other programming languages, C does not have a string type, but treats a string as an array of characters.

Here is some simple code that creates a char array variable and uses printf to print the array variable and a simple piece of information to your screen:

#include <stdio.h>

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

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

$ gcc hello.c --output hello
$ ./hello
hello
Copy the code

function

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

#include <stdio.h>

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

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

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

Conditional statements

In real programming, you usually want your code to make judgments based on data. This is done using conditional statements, of which the if statement is the most basic.

To make the sample program more dynamic, you can include the 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 if the string passed to printmsg is greater than 0:

#include <stdio.h>
#include <string.h>

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;
}
Copy the code

As implemented in this example, this condition can never be untrue, because the supplied string is always Hello, and its length is always greater than zero. The last thing this half-assed reimplementation of the echo command does is accept input from the user.

The command parameter

The stdio.h file contains code that provides two arguments each time the program starts: a count of how many items are contained in the command (argc) and an array of each item (argv). For example, suppose you issue this imaginary command:

$ foo -i bar
Copy the code

Argc is 3 and argv has the following contents:

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

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

Imperative programming languages

C is an imperative programming language. It is not object-oriented and has no class structure. Experience with C can teach you a lot about how to work with data and how to better manage the data generated when your code runs. By using C, you can eventually write libraries that other languages (such as Python and Lua) can use.

To learn more about C, you need to use it. Find useful C header files in /usr/include/and see what little tasks you can do to make C useful to you. In the process of learning, using the C language written by Jim Hall from FreeDOS forget to record. It places all the basics on a double-sided notepad, so you have instant access to all the elements of C grammar as you practice.


Via: opensource.com/article/20/…

By Seth Kenlon (lujun9972

This article is originally compiled by LCTT and released in Linux China