Basic tutorials for using variables in C language programming _c language

Source: Internet
Author: User

C language on the obvious of the number of variables into two categories, integer variables and floating-point numbers, corresponding to the real world of integers and decimals.

The first is an integer, with so many C languages, that every time an integer is used, it is imagined as a binary existence, not a decimal system. The reason is that this is the nature of the program, a little study of the compiler's work will find that in the compiler to handle multiplication and even division, the good compiler is always trying to speed up the program, no doubt in all operations shift operations are the fastest "multiplication" and "division":

1<<2 = 4, 8>>2 = 2

And a normal multiplication is equivalent to a dozen times the addition of the time consumption, displacement is not (division of the consumption is greater, but with the progress of the CPU, these gaps are gradually narrowing, at present, there is still a large gap but in any case optimization, multiplication time will be greater than addition). As mentioned earlier, the C language design is to give the programmer all the right, and the programmer has to do is to control all the control, even the number of calculations, such as in the Good compiler appears:

2*7 ====> (2<<3)-2
5*31 ====> (5<<5)-5

There is no doubt that the compiler-optimized code is much faster than before. That's why we want to consider a number as binary, this is not just the surface, but to be in the deep sense that it is binary, overall, the C language integral is very concise and clear overall divided into signed and unsigned, very good understanding only need to be careful not to let unsigned number of negative operations, here is a principle, Can be very good to avoid this unintentional, do not put unsigned type variables and signed type variables in the same operation, always remember to keep the type of the formula consistent is the design of the protection.

Floating-point number, because the real field can be regarded as dense, so in addition to integers, there are countless decimal, and decimal in the computer how to represent? An infinite state cannot be accurately represented in a computer, so there is a floating-point method, which can be referred to in the book "Deep Understanding of computer systems".
Here is a description of how we should use floating-point numbers correctly in C language. A lot of people (including me) always take it for granted that the computer is omnipotent at the beginning. Even the human can not fully express the decimal computer must be, in fact, is not so, here I can say, the computer is only approximate expression, and the biggest taboo is to compare two floating-point numbers, This article describes a common method of comparison of floating-point numbers, precision method:

 #define DISTANCE 0.00000001 ...
 float f_x_1 = 20.5;
 float f_x_2 = 19.5;
 if (F_x_1-f_x_2 < DISTANCE)
   printf ("They are equal\n");
 else
   printf ("different\n");

So, to a large extent, when you use the floating point in the program, and the direct use of floating point numbers to compare, but found that always can not achieve the desired effect, then you can check whether this is the reason, at this point, have to say is a C language flaw.

A pointer variable, which is a very special variable, is always treated in a special way. Here are a few principles:

    • The addition and subtraction of two unrelated pointers is meaningless
    • Always make sure you can find the allocated memory
    • Whenever and wherever you want to remember, do not use uninitialized pointers to keep unused memory from persisting.

The size of the pointer on a different bit of operating system is not the same, however, under the same operating system, no matter what type of pointer is the same size, which involves the address of the pointer, (digression: C language addressing actually uses the indirect addressing of assembly language, interested in the can try, one way, Using the assembly options of the GCC compiler, generating assembly code for one by one alignment, a general statement of addressing is

4Byte = 32bit
2^32 = 4G

So the 32-bit operating system under the C language pointer:

 ...
 size_t what = sizeof (void*);
 printf ("%d", what);
 ...

Output:

$root @mine:4

For most users, pointers are mainly used to reduce memory consumption and improve operational efficiency, here design a lot of knowledge, I also can not show, more interesting also commonly used two things is increment and grammatical sugar: + +,->

 ...
 int dupli_of_me[10] = {0};//can also use the library function memset () to place the 0
 int *point_to_me = Dupli_of_me;
 int me = m;
 while (Point_to_me < (Dupli_of_me +))
   *point_to_me++ = Me;

where *point_to_me++ = Me; widely used in C language it is equivalent to:

 *point_to_me = Me;
 point_to_me++;

The syntax of sugar, for + +, in unnecessary cases, please use the prefix increment, rather than the suffix increment, because of the consumption problem, think carefully about the two incremental differences where?
Prefix increments are always incremented on the original number, but are suffixes incremented? It first copies a copy of the original number and places it elsewhere, and increment this copy, after the operation of the original number is finished, copy the copy into the original number instead of it, the operation in this more involved, so in unnecessary case, please use prefix increment instead of suffix increment (the same is the same reason).
-> is very widely used in structures:

 typedef struct data{
   int test;
   struct data* next;
 my_struct;
 ...
 My_struct temp;
 My_struct *ptemp = &temp;
 Ptemp->test = m;
 Ptemp->next = NULL;
 if (temp.test = =)
   printf ("correctly!\n");
 else
   printf ("is impossible!\n");
 ...

It can be clearly seen that ptemp->test is actually (*ptemp). The grammatical sugars of test

Variable limit

Const is the most commonly used variable qualifier, which means telling the compiler that the variable or object cannot be changed after initialization, and that it is used to protect some of the necessary return values, parameters, and definitions of constants.

Volatile this keyword is often ignored by the C language textbook, it is very mysterious. Indeed, his role is mysterious: once used, it tells the compiler that even if the variable is not used or modifies other memory cells, its value may change. In layman's parlance, tell the compiler not to use your set of optimization strategies on me.

   /* At this point we will improve the compiler optimization level to-O2     /int Test_num  = 100;//Test an iterative addition
   int     nor_result = 0;
   volatile int vol_result = 0;
   /* Test no volatile Limited, the program's time-consuming     
   /for (int i = 0;i < 10000;++i) for
     (int j = 0;j < 10000;++j)
         Nor_result + = tes T_num;

The next step is to test volatile-qualified code

   for (int i = 0;i < 10000;++i) for
     (int j = 0;j < 10000;++j)
         Vol_result + = Test_num;

After using some means, get run time, can clearly see the difference, on my machine, i5-4cpu, the result is that the latter is about 15 times times slower than the former. In some directions, volatile some of the functions, such as debugging, or some special purpose. Not much involved, so do not record.

Variable description

extern is used to refer to a variable of different files, with external links, to this file. The so-called external link is a variable that can be "seen" other than this file, such as global variables, using the method:

 /* The following is an engineering visible/
 /*file1.c*/
 int glo_show;//for the global variable, they are declared without initialization, then the default initial 0
 int glo_print = 10;//Declaration definition is complete, Automatically allocate memory to store information ...

 /* file2.c/
 extern glo_print;//Only reference name, no additional space
          //So, just write the correct variable name, the rear initialization does not need to be full
          ///Because the initialization of the variable can only be defined once.

 void print ()
 {
   printf ("The globle Value is%d \ n", glo_print);
 }

Auto can be ignored because of no practical significance.

Variable fetch

Formatted input and output in the C language for beginners to use more frequently, but later will find that because I/O operation is too consuming resources, in other words, it will greatly affect the implementation of the program efficiency, will gradually in the release program to eliminate.

Common formatted input standard functions: SACNF, FSCANF, sscanf

For common use, there are two less common formats: '%[' and '%* ',
The former is used to restrict the type of reading, which is common in string filtering (not true filtering)

    scanf ("%d%[a-z]", &tmp, str);
    scanf ("%d%[^i]", &tmp, str);
    scanf ("%d%[^,]", &tmp, str);

Suppose the input is: hello,string to me!
The readings are: Hello and hello,str and hello
The latter ignores the first input:

    scanf ("%*d%d", &tmp);

Suppose the input is: 22 33
Read to: 33
The input that begins with the%*d ignored must match its type, such as input: String 33 will fail to read.
You can also interpret it as a file width, such as when you use printf to format the output:

  Char str[10] = "dir";
  printf ("%*s%s", 4, "", str);
  /* Output:  dir */four blank placeholder  

But in fact, scanf is not very useful, the so-called good use refers to the functional and design defects, always let a lot of people do not touch the mind out of the wrong, often difficult to debug. For example, it retains the input stream of each row, which causes an error to be associated with other input functions, such as fgets or gets, if they are unknown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.