C++ Programmer Alerts - Function Basics and Libraries
(Page 2 of 4 )
Backslash
Consider the following definition:
ifstream InStream(“figuresnumbers.txt”);
Here we are referring to MS-DOS or the Microsoft Windows operating system. For the above statement, you expect that the file being associated with the object InStream is numbers.txt, which can be found in the directory or figures. This is not correct. The n in the file name is interpreted as a new line character by the preprocessor. So the file in question will be considered to contain a new line as its eighth character. Because the newline is an illegal character in an MS-DOS or Microsoft Windows filename, Instream is improperly initialized. To obtain the correct initialization, we must use the literal sequence, as in the following statement:
Ifstream InStream(“figuresumbers.txt”);
PROGRAMMER DEFINED FUNCTIONS
Beware of Global Objects
Global objects affect the entire file. So be careful not to change a global object accidentally. Consider this scenario: a function f() neither changes nor even uses a global object in its body. However, the function f() invokes another function that invokes another function that invokes another function, which changes a global object. Keeping track of this is very difficult; you may not be aware that the global object is ultimately changed and then your entire file may be affected adversely. So avoid using global objects when you can.
ADVANCED PARAMETER PASSING
Compiler Limitations on enforcing the const Modifier
Most C++ compilers will issue an error message if they detect a constant object on the left side of an assignment in a function. However, if a const object is passed by reference to another function, the compiler might issue a warning message only or no message at all. Consider the following:
void f(int &a1, int a2)
{
a1 = a2 + a1 +15;
}
void g(const int CValue)
{
f(Cvalue, 4);
return;
}
In function f(), reference parameter a1 is changed. Of course, there is no problem with this. However, when f() calls g() and passes the const object CValue by reference, the value of CValue could be changed. Most compilers will not issue an error message for this situation. However, some compilers will issue a warning message to tell you that you passed a const object to a function that expects a reference parameter.
In general, when passing a const object to another function, we should make sure that the function the object is passed to does not modify the object. We cannot rely on compilers to catch this potential problem.
You Cannot Redefine Default Parameters
You cannot redefine a default parameter - not even to the same value - within a translation unit. C++ does not allow that. The following code is illegal:
void example(int x, int y = 4); //prototype for function example
…
…
//the definition
void example(int x, int y = 4)
{ //illegal
//body of example
….
}
Next: List >>
More C++ Articles
More By Chrysanthus Forcha