[CPP] Expressions

Expressions are formed from these atomic elements: data and operators. Data may be represented either by variables or by constants. Like most other computer languages, C/C++ supports a number of different types of data. It also provides a wide variety of operations.

Five basic data types

There are five atomic data types in the C subset:
char, int, float, double, and void
The size and range of these data types may vary between processor types and compilers.
In all cases a character is 1 byte.
The size of an integer is usually the same as the word length of the execution environment, can be 16 bits or 32 bits.
To the five basic data types defined by C, C++ adds two more: bool and wchar_t.
enter image description here

Modifying the basic types

You use a modifier to alter the meaning of the base type to fit various situations more precisely. The list of modifiers is shown here:
  • signed
  • unsigned
  • long
  • short
    When a type modifier is used by itself (that is, when it does not precede a basic type), then int is assumed. Thus, the following sets of type specifiers are equivalent:
    enter image description here

Identifier names

In C/C++, the names of variables, functions, labels, and various other user-defined objects are called identifiers.
  • The first character must be a letter or an underscore, and subsequent characters must be either letters, digits or underscores.
  • In an identifier, upper- and lowercase are treated as distinct. Hence, count, Count, and COUNT are three separate identifiers.

Variables

local variables

Variables that are declared inside a function are called local variables. In some C/C++ literature, these variables are referred to as automatic variables. Local variables are not known outside their own code block
C++ support you to define variables at any point within a block

formal parameters

If a function is to use arguments, it must declare variables that will accept the values of the arguments. These variables are called the formal parameters of the function. They behave like any other local variable inside the function. As shown in the following program fragment, their declarations occur after the function name and inside the parentheses:
/* Return 1 if c is part of string s; 0 otherwise*/
int is_in(char *s, char c){
    while(*s){
        if(*s == c) return 1;
        else s++;
    }
}
The function is_in( ) has two parameters: s and c. This function returns 1 if the character specified in c is contained within the string s; 0 if it is not.
They are also dynamic and destroyed upon exit from the function.

Global Variables

Unlike local variables, global variables are known throughout the program and may be used by any piece of code. Also, they will hold their value throughout the program’s execution. You create global variables by declaring them outside of any function. Any expression may access them, regardless of what block of code that expression is in.
enter image description here
On the above program, notice that neither main() nor func1() has declared the variable count, but both may use it.
However, func2(), has declared a local variable called count. When func2() refers to count, it refers to only its local variable, not the global one.
enter image description here
If a global variable and a local variable have the same name, all
references to that variable name inside the code block in which the local variable is declared will refer to that local variable and have no effect on the global variable.
Storage for global variables is in a fixed region of memory set aside for this purpose by the compiler. Global variables are helpful when many functions in your program use the same data. You should avoid using unnecessary global variables, however. They take up memory the entire time your program is executing, not just when they are needed.

const and volatile Qualifiers

There are two qualifiers that control how variables may be accessed or modified: const and volatile

const

Variables of type const may not be changed by your program. (A const variable can be given an initial value, however.) The compiler is free to place variables of this type into read-only memory (ROM).
const int a = 10;//can not be changed
Consider the following code:
enter image description here
The program want to change the space in the string to dash(‘-‘)
However, because *str is const, it is read only and it can not be changed.
enter image description here
You can just print out in this way
Many functions in the standard library use const in their parameter declarations.

strlen() – size_t strlen(const char *str);

Specifying str as const ensures that strlen( ) will not modify the string pointed to by str.
In general, when a standard library function has no need to modify an object pointed to by a calling argument, it is declared as const.

volatile

The modifier volatile tells the compiler that a variable’s value may be changed in ways not explicitly specified by the program.
For example, a global variable’s address may be passed to the operating system’s clock routine and used to hold the real time of the system. In this situation, the contents of the variable are altered without any explicit assignment statements in the program.
May be change by OS, hardware or threading
When the variable is volatile, the system will always read the data from memory again no matter what value it was.
You can use const and volatile together. For example, if 0x30 is assumed to be the value of a port that is changed by external conditions only, the following declaration would prevent any possibility of accidental side effects:
const volatile char * port = (const volatile char *) 0*30;

Storage class specifier

There are four storage class specifier supported by C:

  • external
  • static
  • register
  • auto
    These specifiers tell the compiler how to store the subsequent variable.
C++ adds another storage-class specifier called mutable
so there are 5 storage class specifier in C++

extern

What is linkage in C/C++?

C and C++ define three categories of linkage: external, internal, and none. In general, functions and global variables have external linkage.
This means that they are available to all files that comprise a program.
Global objects declared as static have internal linkage. These are known only within the file in which they are declared. Local variables have no linkage and are therefore known only within their own block.
The principal use of extern is to specify that an object is declared with external linkage elsewhere in the program. To understand why this is important it is necessary to understand the difference between declaration and definition.
  • A declaration declares the name and type of an object.
  • A definition causes storage to be allocated for the object.
  • While there can be a lot of declaration of one object, there can be only one definition for one object.
By preceding a variable name with the extern specifier, you can declare a variable without defining it. Thus, when you need to refer to a variable that is defined in another part of your program, you can declare that variable using extern
enter image description here
extern is declared but not defined, but the global variable below gives it value, even if the value is initialized after main()
If you give that variable an initialization, then the extern declaration becomes a definition. This is important because an object can have multiple declarations, but only one definition.

The important use of extern that relates to multiple-file programs

  • The program can be spread across two or more files, compiled separately, and then linked together
  • There must be some way of telling all the files about the global variables required by the program
  • The best and most portable way to do this is to declare all of the global variables in one file and use extern declarations in the other
  • But in real world, multi-file programs, extern declarations are normally contained in a header file that is simply included with each source code file. This is both easier and less error prone than manually duplicating extern declarations in each file.

static

static variables are permanent variables within their own function or file. Unlike global variables, they are not known outside their function or file, but maintain their values between calls. static has different effect on local variables and global variables

static local variables

When you apply the static modifier to a local variable, the compiler creates permanent storage for it, much as it creates storage for a global variable. The key difference between a static local variable and a global variable is that the static local variable remains known only to the block in which it is declared.
static local variables are very important to the creation of stand-alone functions because several types of routines must preserve a value between calls. If static variables were not allowed, globals would have to be used, opening the door to possible side effects

Example

enter image description here
The output is 23 46
if you don’t use static, the output would be 23 23
Here, we can use global variable, but we need to avoid the conflict between variables. So we use static.
This means that each call to series( ) can produce a new member in the series based on the preceding number without declaring that variable globally
what if you initialize the static value?
You can give a static local variable an initialization value. This value is assigned only once, at program start-up—not each time the block of code is entered, as with normal local variables

static global variables

When applied to a global variable, the static keyword defines the global variable as having internal linkage, meaning the variable cannot be exported to other files. This makes them much safer for use than global variables.
Example again:
int generateID()
{
    static int s_itemID = 0;
    return s_itemID++; // makes copy of s_itemID, increments the real s_itemID, then returns the value in the copy
}
The first time this function is called, it returns 0. The second time, it returns 1. Each time it is called, it returns a number one higher than the previous time it was called. You can assign these numbers as unique IDs for your objects. Because s_itemID is a local variable, it can not be “tampered with” by other functions.

register

The variable will be stored in register(not detailed it here)

评论

此博客中的热门博文

[MLE] Linear Classification

[AIM] MetaHeuristics

[CS231] Neural Networks