C how the programmer uses D programming
Every experienced C programmer has accumulated a series of habits and technologies, which is almost the next day. Sometimes, when learning a new language, these habits will make people can't see the secondary price of the new language because it is too comfortable. So some common C technology is collected below, and how the same tasks are completed in D.
Since C does not object-oriented features, see how C programmers use D programming.
C The preprocessor discussed in the pre-procedure VS D of C.
Getting a type of size to get a type of maximum value and minimum value basic type Special floating point value floating point division in the floating point comparison, all elements of the NAN asserts initialized array traverses the entire array creation variable size array string Connection Format The Print Function Before the Print Function Between Unfamiliar Function Band Number Break and Continue Goto Statement Structure Tagname Space Find Strings Set Structure Members Alignment Anonymous Structure and Joint Declaration Structure Types and Variables Get Structural Members' Offset Union Initialization Structure of Initialization Structure Initialization String Qu Qu Qu Qu ISCII Character VS Wide Character The Create Array Create a New TypeDef Type Comparison Structure Comparison String Sequencing Access Visual Division Square Strings Data Traversing Data Structural unsigned right shift
Get a type of size
W method
SIZEOF (int)
SIZEOF (Char *)
Sizeof (double)
SIZEOF (Struct Foo)
D method
Use the SizeOF attribute:
Int.sizeof
(char *). SIZEOF
Double.sizeof
Foo.sizeof
Get a type of maximum and minimum value
W method
#include
#include
Char_max
Char_min
Ulong_max
DBL_MIN
D method
Char.max
Char.min
Ulong.max
Double.min
basic type
Type of D in D in Type C
BOOL => bit
Char => char
Signed char => Byte
UNSigned char => ubyte
Short => short
Unsigned short => ushort
Wchar_t => wchar
INT => int
unsigned => uint
Long => int
unsigned long => uint
Long long => long
Unsigned long long => ULONG
Float => float
Double => DOUBLE
Long double => extended
_Imaginary long double => iMaginary
_Complex Long Double => Complex
Although char is a type of no symbol 8 bit, Wchar is a type of no symbol 16 bit, which is also classified to support overload parsing and type security. The size of the integer types and unsigned types in C is not fixed (different implementations can be different); their size is fixed.
Special floating point value
W method
#include
Nan
Infinity
#include
DBL_DIG
DBL_EPSILON
DBL_MANT_DIG
DBL_MAX_10_EXP
DBL_MAX_EXP
DBL_MIN_10_EXP
DBL_MIN_EXP
D method
Double.nan
Double.infinity
Double.dig
Double.epsilon
Double.mant_dig
Double.max_10_exp
Double.max_exp
Double.min_10_exp
Double.min_exp
The remainder in floating point division
W method
#include
Float f = fmodf (x, y);
Double D = FMOD (X, Y);
Long Double E = FMODL (X, Y);
D method
D Supports the residual ('%') operator of the floating point operation:
Float f = x% y;
Double D = x% y;
Extended E = X% Y;
Treatment in floating point comparison
W method
C The result of the comparison of the operand is NaN is not defined, and few C compilers check this (the DIGITAL MARS C compiler is an exception, the DM compiler checks if the operand is NAN).
#include
IF (isnan (x) || Isnan (Y))
Result = false;
Else
Result = (x D method D comparison and operators provide full support to the NAN parameters. Result = (x As a result of all defense coding strategies W method C does not directly support the assertion, but it supports __file__ and __line__, which can use macro-archive assertions based on their basis. In fact, in addition to the assertion, __ file__ and __line__ have no other actual use. #include Assert (e == 0); D method D Directly constructed the assertion in the language: Assert (e == 0); [Note: Tracking function? ] All elements of initialization array W method #define array_length 17 Int array [array_length]; For (i = 0; i Array [i] = value; D method Int arch [17]; Array [] = value; Traverse the entire array W method Array lengths are additionally defined, or use clumsy SizeOf () expressions. #define array_length 17 Int array [array_length]; For (i = 0; i Func (Array [i]); Or: int arch [17]; For (i = 0; i Func (Array [i]); D method You can use the "Length" property to access the length of the array: Int arch [17]; For (i = 0; i Func (Array [i]); Or use a better way: Int arch [17]; Foreach (int value; array) Func (Value); Create a variable size array W method C cannot handle this array. Need to create a variable to save the length and explicitly manage the array size: #include Int Array_Length; Int * array; INT * NEWARRAY; NEWARRAY = (int *) Realloc (Array, (Array_length 1) * sizeof (int)); IF (! NEWARRAY) Error ("Out of Memory"; Array = NEWARRAY; Array [array_length ] = x; D method D supports a dynamic array that can easily change the size. D Supports all necessary memory management. array; Array.Length = array.length 1; Array [array.length - 1] = x; String connection W method There are several puzzles that need to be solved. If you can release memory, how to handle the empty pointer, get the length of the string and memory allocation: #include Char * s1; Char * s2; Char * S; / / Connect S1 and S2 and store the results in S Free (s); S = (char *) Malloc ((S1? Strlen (S1): 0) (S2? Strlen (S2): 0) 1); IF (! s) Error ("Out of Memory"; IF (S1) STRCPY (S, S1); Else * s = 0; IF (S2) STRCPY (S Strlen (s), S2); // Add "Hello" to the tail Char hello [] = "hello"; Char * news; SIZE_T LENS = S? Strlen (s): 0; News = (char *) Realloc (S, (Lens SizeOf (Hello) 1) * Sizeof (char)); IF (! news) Error ("Out of Memory"; S = News; Memcpy (S Lens, Hello, Sizeof (Hello); D method D is overloaded for the CHAR and WCHAR arrays, respectively, the '~' and '~ =' operators are used to connect and add: CHAR [] S1; Char [] s2; CHAR [] S; S = S1 ~ S2; s ~ = "hello"; Format print W method Printf () is a general formatted print routine: #include Printf ("Calling All Cars% D Times! / N", NTIMES); D method What can we say? Here is the world of Printf (): IMPORT STDIO; Printf ("Calling All Cars% D Times! / N", NTIMES); (Translation: In fact, there is already two functions of Write and Writeln in the standard library Phobos, but it has not been fixed.) Before the forward reference W method Functions that have not been declared have not been cited. Therefore, if the function has not appeared in the source file, the function declaration must be inserted before the call. Void forwardfunc (); void myfunc () { ForwardFunc (); } Void forwardfunc () { ... } D method The program is seen as a whole, so there is no need to write forward statements, and this is not allowed! D Avoid the cumbersome pre-written function declarations and errors caused by repeated preparation of forward function declarations. The function can be defined in any order. void myfunc () { ForwardFunc (); } Void forwardfunc () { ... } No parameter function W method Void function (void); D method D is a strong type language, so there is no need to explicitly explain that a function does not have a parameters, just do not write parameters when declaring. Void function () { ... } Break and Continue with labels W method Break and Continue are only used in nested innermost loops or Switch structures, so you must use GOTO to implement multi-layer BREAK: For (i = 0; i <10; i ) { For (j = 0; j <10; j ) { IF (j == 3) Goto Louter; IF (j == 4) Goto L2; } L2: ; } Louter: ; D method After Break and Continue statements, you can bring a label. This label is periphery of the loop or Switch structure, and Break is used to exit the cycle. Louter: For (i = 0; i <10; i ) { For (j = 0; j <10; j ) { IF (j == 3) Break Louter; IF (j == 4) CONTINUE LOUTER; } } // BREAK LOUTER jumps here GOTO statement W method Goto statement that is criticized is an important tool for professional C programmers. Sometimes this is the necessary supplement to the control flow statement. D method Many C mode GOTO statements can be replaced using the label Break and Continue statements in D. But D is a practical language for actual programmers. They know when to break the rules. So, Dust support GOTO! Structure marker name space W method Every time I write the struct keyword to the structural type name, it is jealous, so the usage of habits is: Typedef struct abc {...} ABC; D method The structure tag name is no longer located in a separate name space, and they share a namespace with ordinary names. therefore: Struct ABC {...}; String string W method A string is given, comparing the same series of possible values, if the match is implemented. The typical application of this method is handled. #include { ENUM STRINGS {Hello, Goodbye, Maybe, Max}; Static char * TABLE [] = {"Hello", "Goodbye", "Maybe"} INT I; For (i = 0; i { IF (Strcmp (S, Table [i]) == 0) Break; } Switch (i) { Case Hello: ... Case Goodbye: ... Case Maybe: ... DEFAULT: ... } } The problem is to maintain three parallel data structures: enumeration, table, and Switch-case structure. If there are a lot of values, it is not so easy to maintain the correspondence between the three data structures, so this situation has become a hotbed that is born BUG. In addition, if the number of values is large, it is greatly improved with a binary look or hash table relative to a simple linear lookup. But they need more time to coding, and debugging is more difficult. Typically, people simply abandon these efficient and complex data structures. D method D extended the concept of the switch statement, now it can process strings like processing numbers. Therefore, the implementation of string lookup is directly: Void dostring (char [] s) { Switch (s) { Case "Hello": ... Case "Goodbye": ... Case "Maybe": ... DEFAULT: ... } } Adding a new Case clause becomes easy. It can be generated by the compiler to generate a fast lookup scheme, which avoids the time and the introduced bug due to manual encoding.