C + + Syntax summary, syntax query __c++

Source: Internet
Author: User
Tags arithmetic bitset bitwise cos exception handling function definition sin throw exception

How to program in C + +
Http://cs.fit.edu/~mmahoney/cse2050/how2cpp.html

How to program in C + +

You could copy this file to noncommercial use. The latest version is located at cs.fit.edu/~mmahoney/cse2050/how2cpp.html updated APR. 14, 2010. Please have a errors to Matt Mahoney at mmahoney@cs.fit.edu. Seldom-used features have been deliberately omitted. Language Summary

Basic Concepts

Statements if, for, while, return, break ...

Expressions arithmetic, comparison, assignment ...

The most important types are int, char, bool, double, and the containers string, vector, and map. Summary of common types:

Built-in        Description
int x;          Fastest integer type (16-32 bits), also short, long, unsigned
char x;         8-bit character, ' to ' \xff ' or-128 to 127
double X;       Bit real + or-1.8e308, significant digits, also float
bool x;         True or false                     
               
modifiers       Description
const T x;      Non-modifiable object
t& y=x;         Reference, Y is a alias for X, which both have type T
f (...) {...}  Defines f as a function returning T
t* p;           Pointer to T (*p is a T object)
T a[n];         Array of N elements of T, A[0] to a[n-1]
static T x;     Place x in data segment
register T x;   (rare) Hint to optimize for speed
volatile T x;   (rare) x may modified externally
The following standard library types and functions require at the beginning of the program:
  #include  

C + + allows to create your own types and libraries. The most important type is a class, allowing object oriented programming. The class A is the abstract data type with a hidden representation and a set of public member functions and types. Classes can be organized into a hierarchy (inheritance), and you can write code so accepts any type in this hierarchy (p olymorphism). Functions and classes can parameterized by type (templated).

Class T {...};  Defines T as a collection of types, objects, and member functions template <class t>
... Defines a set of functions or classes over the all T
typedef t U;    Defines type U is a synonym for T
enum t {...};   Defines t as an int, and set of int constants
struct T {...}; Like a class, except default scope of the members are public
union T {...};  A struct with the object members overlapping in memory
namespace N {...};  Defines a scope for a collection to types, objects, and Functions program

organization (compiling, linking, make) 
   history of C + +
further Reading

Basics

C + + is a compiled language, a upward compatible superset of C and a (incompatible) predecessor to Java. C + + compiles C programs but adds object oriented (OO) features (classes, inheritance, polymorphism), Templates (Generic Fu Nctions and classes), function and operator overloading, namespaces (packages), exception handling, a library of standard Data structures (string, vector, map, etc.) and formatted text I/O (IStream, ostream). Unlike Java, C + + lacks a standard graphical user interface (GUI), network interface, garbage collection, and threads, and Allows Non-oo programming and unchecked low-level machine with operations. However, C + + executes faster than Java and requires no run-time support.

A C + + program is a collection of function, object, and type declarations. Every program must have a Function int main () {...}  where The curly braces enclose a block, a sequence of declarations and statements ending in semicolons which EXE Cuted in order. A statement is a expression, blocks, or control statement that alters "order of execution", such as if, while, for, Break and return. Some types (std::string), Objects (std::cout), and functions are defined in header files, requiring the line  #include

  Comment:prints "Hello world!" and an os-independent newline
  #include <string>    //defines type Std::strin G
  #include <iostream>  //Defines global object Std::cout
  using namespace std;//Allow std:: to be Dropp Ed
  int Main () {         //Execution starts here
    string s= "Hello world!\n";//Declares object s of type String
    Co UT << s;         An expression as a statement, << are the output operator return
    0;          Execution ends here
  }

The symbol//denotes a comment to the "end of" the line. Also use/* ... * for multiline comments. Spacing and indentation are used for readability. C + + is mostly free-form, except "The end of", significant after # and//. C + + is case sensitive.

C + + source code files should be created with a text editor and have the extension. cpp. If the above is called hello.cpp, it would be compiled and run as follows in a UNIX shell window:

  g++ hello.cpp-o Hello-wall-o
  ./hello
The-o option renames the executable file, by default a.out. -wall turns on all warnings (recommended). -O optimizes (compiles slower but runs faster).

In Windows, the GNU C + + compiler is called DJGPP. To compile and run from a MS-DOS box:

  gxx hello.cpp-o hello.exe
  Hello
The output file must have a. EXE extension (default is A.EXE). There is also a. OBJ file which you can delete.

To use the network or GUI interface on UNIX, you must use the X and socket libraries, which don ' t work in Windows. In Windows, your must use the Windows APIs and a compiler that supports them, such as from Microsoft, Borland, or Symantec. Gui/network programming is nonportable and outside the scope of this document.

Links to free and commercial C + + compilers can is found at cplusplus.com. Statements

A program consists of a collection of functions (one of which must is int main () {...}) and type and object declarations. A function may contain declarations and statements. Statements have the following forms, where S is a statement, and T is a true/false expression.

S                              Expression or declaration;                        Empty statement {s; s;}                      A blocks of 0 or more statements is a statement if (t) s; If T is true then s if (t) s;              else S;                   else is optional while (t) s;             Loop 0 or more the for (S1 t; s2) s; S1;                         while (t) {s; s2;} break;                      Jump from while, for, does, switch return x;                 return x to calling function try {throw x;}               Throw exception, Abort if not caught, X has any type catch (T y) {s;} If x has type T then y=x, jump to S catch (...)               {s;} else jump here (optional) do s;               while (t); (uncommon) s;
while (t) s;                      Continue (uncommon) Start Next loop of while, for, do switch (i) {//(uncommon) Test int expression I to cons T C case c:s;    Break          if (i==c) go to here default:s;             Optional, else go here} Label:goto label;
 (rare) Jump to label within a function

A statement may is a declaration or an expression. Objects and types declared in the block of block are. (functions cannot be defined locally). It is normal (but not required) to show statements on separate lines and to indent statements enclosed in a block. If braces are optional, we indent anyway. For instance,

{                     //start of block
  int a[10], i=0, J;  Declaration
  a[i+2]=3;           Expression
}                     //End of blocks, a, I, and J are destroyed
Declares the array of int a with elements a[0] through a[9] (whose values are initially), I with undefined value 0 , and J with an undefined initial value. These names can are used in scope, which are from the declaration to the closing brace.

The For loop are normally used for iteration. For instance, the following both exit the loop with I set to the index of the the ' the ' the ' A such that A[i ' is 0, or T o If not found.

  for (i=0; i<10; i=i+1) {    i=0;
    if (a[i]==0) {while            (i<10) {break
      ;                    if (a[i]==0)
    } break                             ;                             i=i+1;
                              }
The braces in the for loop are optional because they all enclose a single statement. In the while loop, the outer braces are required because they enclose 2 statements. All statements are optional:for (;;) loops forever. The the statement in a for loop may declare a variable the local to the loop.
  for (int i=0; i<10; i=i+1)

It is only possible to break from the innermost loop of a nested loop. Continue in a For loop skips the rest of the But executes the iteration (S2) and test before the next loop.

return x; Causes the ' current function ' to ' the ' caller, evaluating to X. It is required except into functions returning void, in which case return; Returns without a value. The value returned by main () has no effect on program behavior and is normally discarded. However It is available as the $status in a UNIX csh script or errorlevel in a Windows. BAT file.

  int sum (int x, int y) {  //Function definition return
    x+y;
  }
  int main () {
    int a=sum (1,2);        A=3;
    return 0;              By convention, nonzero indicates a error
  }

A test of several alternatives usually has the form if (t) s; else if (t) s; else if (t) s; .. else S;. A switch statement is A optimization to the special case where an int expression is tested against a small range of cons Tant values. The following are equivalent:

  switch (i) {                if (i==1) case
    1:j=1;         J=1;
    Case 2://Fall thru      else if (i==2 | | i==3)//| | means ' or else ' case
    3:j=23;        j=23;
    default:j=0;             Else
  }                             j=0;

Throw x jumps to the "the" of the statement of the most recently executed try block where the parameter declaration matches The type of x, or a type that x can and converted to, or is .... At most one catch block is executed. If no matching catch block are found, the program aborts (unexpected exception). Throw With no expression in a catch block throws the exception just caught. Exceptions are generally used when it was inconvenient to detect and handle a error in the same place.

  void F () {
    throw 3;
  }

  int main () {
    try {
      f ();
    }
    catch (int i) {  //Execute this block with i = 3
      throw;        Throw 3 (not caught, so program aborts)
    }
    catch (...) {    //Catch any other type
    }
  }
Expressions

There are levels of operator precedence, listed highest to lowest. Operators at the same level are evaluated left to right unless indicted, Thus, a=b+c means a= (b+c) because + is higher tha n =, and a-b-c means (a-b)-C. Order of evaluation are undefined, e.g. for sin (x) +cos (x) We cannot say sin () or cos ( ) is called.

The meaning of a expression depends on the types of the operands. (x,y) denotes a comma separated list of 0 or more objects, e.g. (), (x), or (1,2,3,4).

1 x::m member M of namespace or class X:: M Global name M if otherwise hidden by a local declaratio           N 2 p[i] i ' th element of container p (array, vector, string) X.M member M of object x p->m Member m of object pointed to by P F (x,y) Call function f with 0 or more arguments i++ ADD 1 to I,       Result is original value of I i--subtract 1 to I, result is original value of I static_cast<t> (x)  Convert x to type T using defined conversions const_cast<t> (x) (rare) Convert X to equivalent but T reinterpret_cast<t> (x) (rare, dangerous) pretend X has type T dynamic_cast<t> (x) (rare) Convert base Pointer or reference to derived if possible typeid (x) (rare) If x are type T, then typeid (x) ==typeid (t) (in <typein  fo>) 3 (right to left) *p Contents of pointer P, or p[0]. If p is type t*, *p was T &x address of (pointer to) x. If x is type T, &x is t*-a Negative of numeric a!i not I, true if I is false or 0 ~i
bitwise compliment of I, -1-i (t) x Convert (cast) object x to type T (by static, const, or reinterpret)  T (x,y) Convert, initializing with 0 or more arguments new T Create a T object on heap. As t* new T (x,y) Create, initializing with 0 or over arguments new (p) t (rare) Initialize t at address P Withou T allocating from heap new (p) t (x,y) (rare) Initialize T with 0 or over arguments at p new T[i] Create array of i O  Bjects of type T, return t* pointing to-a delete P Destroy object pointed to by P obtained with new T or            New T () delete[] p Destroy Array obtained with new t[] ++i Add 1 to I, and result is the new I-I. Subtract 1 from I, result is the new I sizeof x size of object x in bytes sizeof (t) Size of objects of type T I         N bytes 4 x.*p  (rare) object in x pointed to by pointer to member P Q-&GT;*P (rare) Object in *q pointed to by Pointer to member P 5 a            *b Multiply Numeric A and B. Divide numeric A and B, round toward 0 if both are integer i%j Integer remainder I-(i/j) *j 6 a+b addition, string concatenation a-b subtraction 7 x<< Y integer x shifted y bits to left, or output y to ostream x x>>y integers x shifted y bits to RI Ght, or input y from IStream x 8 x<y less than x>y Greater than x<=y less than O            R equal to X>=y Greater than or equal to 9 x==y equals x!=y not equals i&j bitwise AND of integers I and j i^j bitwise XOR integers i and j I|j bitwise OR integers i and J i&&j I and then J (Evaluate J only if I are True/nonzero) i| | J I or else J (evaluateJ only if I am False/zero (right to left) X=y Assign y to X, the result is new value of x x+=y x=x+y        , also = *=/=%= &= |= ^= <<= >>= i?x:y If i is True/nonzero then x else y throw X
 Throw exception X (any type) of X,y Evaluate x and Y (any types), the result is Y
Expressions that don ' t require creating a new object, such as A=b, ++a, P[i], p->m, X.M, A?b:c, a,b, etc. are lvalues, M Eaning they may appear on the left side of a assignment. The other expressions and conversions create temporary objects to hold the result, which are const (constant). An expression used as a statement discards of final result.
  int A, B, C;
  A+b;         Legal, add a and B, discard the sum
  a=b=c;       Legal, assign C to B, then assign the new B to a
  (a+=b) +=c;   Legal, add B to a, then add C to a
  a+b=c;       Error, A+b is const
  double (a) =b;//error, double (a) is const

Static_cast<t> (x) converts x to type T If a conversion is defined. Usually the value of x is preserved if possible. Conversions are defined between all numeric types (including char and BOOL), from 0 to pointer, pointer to bool or void*, IStream to bool, the ostream to bool, the char* to string, the from a derived class to base class (including pointers or references), and from type T to type U if Class U has a constructor taking T or Class T has a member operator U (). A conversion'll be implicit (automatically applied) whenever a otherwise invalid expression, assignment, or function ar Gument can be made legal by applying one, except for T-u where u ' s constructor taking T is declared explicit, for Examp Le, the constructor for vector taking int.

Related Article

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.