Saturday, December 29, 2012

Thinking in C++

Thinking in C++
1. 
Even those people who were smiling and nodding were confused about many issues. 
C++ uses static type checking because the language cannot assume any particular runtime support for bad operations. Static type checking notifies the programmer about misuses of types during compilation, and thus maximizes execution speed.

A gotcha


There is a significant difference between C and C++ for functions with empty argument lists. In C, the declaration:
int func2();

means “a function with any number and type of argument.” This prevents type-checking, so in C++ it means “a function with no arguments.”
In both C and C++, the declaration func(void); means an empty argument list. 



The keyword is extern. It can mean the definition is external to the file, or that the definition occurs later in the file.

Declaring a variable without defining it means using the extern keyword before a description of the variable, like this:
extern int a;

extern can also apply to function declarations. For func1( ), it looks like this:
extern int func1(int length, int width);

In the function declarations, the argument identifiers are optional. In the definitions, they are required (the identifiers are required only in C, not C++).
extern float f(float); // Function declaration

File names in double quotes, such as:
#include "local.h"

tell the preprocessor to search for the file in (according to the specification) an “implementation-defined way.” What this typically means is to search for the file relative to the current directory. If the file is not found, then the include directive is reprocessed as if it had angle brackets instead of quotes. 

C comments start with /* and end with */. They can include newlines. C++ uses C-style comments and has an additional type of comment: //.


 a general guideline for C++ programming is that you should always initialize a variable at the point of definition. 
Pointers work roughly the same in C and in C++, but C++ adds an additional way to pass an address into a function. This is pass-by-reference
The difference between references and pointers is that calling a function that takes references is cleaner, syntactically, than calling a function that takes pointers (and it is exactly this syntactic difference that makes references essential in certain situations).

There’s one other type that works with pointers: void. If you state that a pointer is a void*, it means that any type of address at all can be assigned to that pointer (whereas if you have an int*, you can assign only the address of an int variable to that pointer).
//: C03:CastFromVoidPointer.cpp
int main() {
  int i = 99;
  void* vp = &i;
  // Can't dereference a void pointer:
  // *vp = 3; // Compile-time error
  // Must cast back to int before dereferencing:
  *((int*)vp) = 3;
} ///:~

3: The C in C++

Defining variables on the fly


No comments:

Post a Comment