Des, prog & doc.

Design
patterns and anti-patterns
Programming
Writing snippets for visual assist
C preprocessor and fun Macros
Google on c++
Coding advises
Documenting
File Header style
Self Documenting Code

Define Guard (google style) in Visual Assist


#ifndef $FILE_BASE_UPPER$_$FILE_EXT_UPPER$_
#define $FILE_BASE_UPPER$_$FILE_EXT_UPPER$_

$clipboard$

#endif  // $FILE_BASE_UPPER$_$FILE_EXT_UPPER$_

Clamp variable to interval


#include <iostream>
using namespace std;

float Clamp( float a )
{
 float v = (a<0) ? 0 : (a<1) ? a : 1;
 return v;
}

int main ()
{
 cout<< -3 << "\t" << Clamp(-3) <<endl;
 cout<< 0.5f << "\t" << Clamp(0.5f) <<endl;
 cout<< 3 << "\t" << Clamp(3) <<endl;
}

Output

 -3      0
0.5     0.5
3       1

You can modify function to take interval , or use it as preprocessor directive.

Anonymous Structures

Found on MSDN

A Microsoft C extension allows you to declare a structure variable within another structure without giving it a name. These nested structures are called anonymous structures. C++ does not allow anonymous structures.You can access the members of an anonymous structure as if they were members in the containing structure.

 


// anonymous_structures.c
#include

struct phone
{
int  areacode;
long number;
};

struct person
{
char   name[30];
char   gender;
int    age;
int    weight;
struct phone;    // Anonymous structure; no name needed
} Jim;

int main()
{
Jim.number = 1234567;
printf_s("%d\n", Jim.number);
}

Static Initialization Function in Classes

Content

Sometime when we write a C++ class, we want a static function is used to initialize the class. For example, a static function is used to initialize a static vector or map. We can do the same thing easily in Java, by Java’s static block. How we can do with C++?

At first, let’s see how to initialize a normal static member in C++.

class Test1
{
    public:static string emptyString;
};
string Test1::emptyString = "";
// also can be
// string Test1::emptyString;
// string Test1::emptyString("");

Continue reading