You are on page 1of 12

Incompatibilities / Differences between C and C

++

Lab 2 C++

Incompatibilities / Differences between C and C++
1. Objectives
1. The resolution operator
2. The operators new and delete
3. Inline functions
4. Functions returning a reference data type
5. Call by reference and call by value
6. The Boolean data type
7. Default parameters for functions
8. The reference type
9. Overloading functions

2. Incompatibilities between C and C++
2.1 Declaring and defining functions in C++
Alternative 1

Alternative 2

#include "stdafx.h"
using namespace std;

#include "stdafx.h"
using namespace std;

void twotimes (int a)
{
cout<<a;
a=a*2;
cout<<" doubled is "<<a;
}

void twotimes(int);

void main()
{
//system("color fc");
twotimes(10);
_getch();
}

void main()
{
twotimes(10);
_getch();
}
void twotimes(int a)
{
cout<<a;
a=a*2;
cout<<" doubled is "<<a;
}

Both alternatives are correct in C++.
Do not forget to declare the prototype of a function before call it.
2.2 Void pointers
There is NO default conversion of pointers from the type "void*" in other types of
pointers.

int *ip. } 2) Try to add more comments when writing source code! 3) Do not put more than 90 characters on one line! 3. v[100]. i++. // some computations… return counter. Example: a program which returns true if an element is found in an array and false otherwise. while (i<n) { cout<<"v["<<i<<"]= ".Incompatibilities / Differences between C and C++ Lab 2 C++ For the type (void*) C++ allows the default conversion from: the type of the pointer -> void* Example: void * vp. vp = ip. cin>>n. } Is more explicit and used than: int cnt(char* str) { int i. Improvements of C++ Suggestions: 1) Use more explicit names for functions and for variables.elem. return i. } . //correct in C and in C++ ip=vp. //correct in C and C++ 3. cout<<"Introduce the length of the array "<<endl. int i=0.n. C does not have this data type. cin>>v[i]. incorrect in C++ ip = (int*)vp. Example: int countSpaces(char* str) { int counter. //correct in C. bool find_elem() { bool found=false.1 The boolean type The boolean type is a basic data type in C++.

cin>>nume. cin>>elem.23). but be carefull to declare them before using them! Example: #include <iostream> using namespace std.i++) { if (elem==v[i]) { found=true. cout<<"What is your name? "<<endl. cout) .y. } . cin>>x>>y. for (i=0.z. //call the function directly in cout //only in the case when the function returns a value // (is not void) z=23+sum(10. In order to use them we have to include the iostream library and we have to declare the use of the standard namespace std using namespace std.y). //read x and y cout<<"the sum of "<<x <<" and "<<y<<" is "<<sum(x.We use cout for printing on the screen (cout – console output – stdout) .i<n.We use cin for storing a new entry (cin – console input – stdin) Both are included in the iostream library. } 3.2 I/O console (cin. } void main() { int x. cout<<"Introduce x and y "<<endl. } } return found. int sum (int a. char name[20].3 Facilities to statements In C++ you can declare the local variables anywhere inside the body of a function. cout<<"Wow! "<<nume<<" is such a beautiful name!".Incompatibilities / Differences between C and C++ Lab 2 C++ cout<<"Introduce the elementul you search for ". 3. cout<<"z= "<<z. int b) { return (a+b).

. int &refint=number. float &refvar=variabile. intersch(&a. void main() { int a..&b). the number = "<<numar<<" and refint = "<<refint<<endl. but will allocate memory for a float variabile. cout<<"the interchanged values are "<<a <<" and "<<b. for example. cout<<"Give a and b "<<endl. //reference to int. a = b. } void main() { int a. } An example of interchanging two numbers The C version The C++ version void intersch(int *a.b). } If. int&b). cout<<"AFTER. they have different types. ATTENTION!! The data type of the reference variable and of the variable with which is instantiated has to be the same. cin>>a>>b. int *b) { int aux. cout<<"Give a and b "<<endl. This reference variable has to be instantiated when declaring it with the address of a variable which is already defined.b. cout<<"the interchanged values are "<<a <<" and "<<b. void main() { int number=10. auxiliary = a. } void intersch1(int &a. *a=*b. therefore a hidden object will be created for the given reference.b.4 Reference variables In C++ we can declare identifiers as references to objects of a certain data type. aux=*a. *b=aux. refint=200. } void intersch1(int &a. The compiler will not create a reference to a variable int. HAS TO be instantiated cout<<"the number is "<<number<<" and refint = "<<refint<<endl. //automatically number=200.Incompatibilities / Differences between C and C++ Lab 2 C++ 3. we have: int variabile. intersch1(a. cin>>a>>b. int&b){ int auxiliary. b = auxiliary.

refy.5 Functions which return references struct book { char author[64]. int z) { x=10. } void function_call_by_pointer_reference(int *x.refz). 54. int &y. y=20. function_call_by_pointer_reference(&x. int &z) { x=10. cout<<"By value "<<x<<" "<<y<<" "<<z<<endl. float price. 49.9}. function_call_by_value(x.9}. char title[64]. "1001 Visual Basic Programmer's Tips". } void function_call_by_reference(int &x. z=30. } void main() { int x=10. else return(library[0]). *z=30.Incompatibilities / Differences between C and C++ Lab 2 C++ 3 ways of parameter passing: void function_call_by_value(int x. function_call_by_reference(refx. y=20. int &refx=x.&z). } 3. int &refy=y. book library[3] = { {"Jamsa and Klander". {"Klander".9}}. 54. cout<<"By reference "<<x<<" "<<y<<" "<<z<<endl. int *y. z=30. "Hacker Proof". {"Jamsa and Klander". int y. z=30.y. cout<<"By pointer "<<x<<" "<<y<<" "<<z<<endl.&y. book& give_abook(int i) { if ((i >= 0) && (i < 3)) return(library[i]). *y=20. . int *z) { *x=10.z). y=20. int &refz=z. "All about C and C++". }.

// cout<< divide(). This allows us to call the function in several ways. float f. Example: int divide(int a. function1(11). return result. //correct call // functie(11.100).6 Parameters with default values In C++ we can declare functions with parameters which have default values. but with a different number of parameters and a different return value.9.title. cout<< divide(20. .7 Overloading function names C++ allows us to have two or more functions with the same name. float=23.price.author << ' ' << a_book.10)<<endl. } 3. } void function1(int i. } void function1(int.h" using namespace std. long l) { cout<<"i= "<<i<<" f= "<<f<<" l= "<<l<<endl.5. } 3. Example: #include "stdafx. //incorrect float f=4.f). int b=4) { int result. cout << a_book. int main() { cout<< divide(15)<<endl. book& a_book = give_abook(2). result=a/b. The arguments with default values have to be at the end of the parameter list. long=100). // incorrect call return 0. cout << ' ' << a_book.// correct call function1(11. // correct call function1(11.6).Incompatibilities / Differences between C and C++ Lab 2 C++ } void main(void) { cout << "Almost getting the book \n".2.

0. } char * operation(char *s1. cout << operation(x.m). Ex: #define Max(a. float n=5. char *s2) { char *result = new char[strlen(s1)+strlen(s2)+1]. } You can use the inline functions when you have a small number of parameters and not many instructions.. for an assessment with respect to the precedence of the operators.Incompatibilities / Differences between C and C++ Lab 2 C++ int operation(int a. } float operation(float a. ) { instructions .s2)<<endl. strcpy(result.. s2).y=2. cout << "\n". The advantage of using inline functions is an increased execution speed.. } int main () { int x=5. s1). cout << operation(n. return 0. } 3. int b) { return (a*b).. strcat(result.m=2. return result. char *s1="The first string ".8 Inline functions Syntax: inline data type name (parameters . float b) { return (a/b). cout<<"Adding to strings "<<operation(s1. *s2="The second string ". cout << "\n".b) ((a)<(b)) ? (b) : (a) . The inline functions replace the macros built using #define and avoid the difficulties caused by these macros: .y).the parameters should be specified in parentheses.0.these functions do not return values .

temp = *a. i++) swap_inline(&a. stop = clock(). *c = *d. for (i = 0. d = 4. stop. } void main(void) { clock_t start. temp = *a. } void swap_call(int *a.Incompatibilities / Differences between C and C++ Lab 2 C++ inline int Max(int a. &b. b = 2. int *c. temp = *c. } Study the following example which prints the running time when calling 30000 times each function #include "stdafx. long int i. &b. int a = 1. &d). i < 300000L. int *d) { int temp. &c. stop = clock(). cout << "Time for inline: " << stop . *d = temp. int *b. *b = temp. i++) swap_call(&a. start = clock(). *a = *b. &c. *c = *d.h> using namespace std. *a = *b. *b = temp. int *b. int *c. int *d) { int temp. .h" #include <time. c = 3. *d = temp. temp = *c. i < 300000L. for (i = 0. int b) { return (a<b) ? b : a . start = clock().start. inline void swap_inline(int *a. &d).

Until now. we have only had as much memory available as we declared for our variables. void main() { int global_variable=100. i < 256. } 3.h" using namespace std. In C++ we have two new operators for memory management (dynamic memory): . But. } 3. i++) cout << array[i] << ' '. for (i = 0. for (i = 0. delete [] str.Incompatibilities / Differences between C and C++ Lab 2 C++ cout << "\nThe running time for calling the function is: " << stop start. int i. what if we need a variable amount of memory that can only be determined during runtime? For example. in all our programs. i < 256. .10 The resolution operator Example: #include "stdafx.new – for memory allocation . in the case that we need some user input to determine the necessary amount of memory space.delete – the memory is freed Ex: int main() { char * str = new char [100]. i++) array[i] = 'A'.9 New operators: new and delete In C the memory management is implemented in auxiliary libraries and the user can use some functions. having the size of all of them to be determined in the source code. } What is the effect of the following program? void main(void) { char *array = new char[256]. int global_variable=300. before the execution of the program.

functions.Incompatibilities / Differences between C and C++ Lab 2 C++ cout<<"the value of the local variable is "<< global_variable<<endl. classes etc. } Keywords in C++ asm auto bad_cast bad_typeid bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum except explicit extern false finally float for friend goto if inline int long mutable namespace new operator private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try type_info typedef typeid typename union unsigned using virtual void volatile while xalloc Remark: The keywords cannot be used as names for variabiles. cout<<" the value of the global variable is "<<::global_variable<<endl. .

Incompatibilities / Differences between C and C++ Lab 2 C++ Operators in C++ The C++ operators (from the highest to the lowest priority) are: :: :: [] () () . -> ++ -new delete delete[ ] ++ -* & + ! ~ sizeof sizeof ( ) typeid( ) (type) const_cast dynamic_cast reinterpret_cast static_cast .* ->* * / % + << >> < > <= >= == != & ^ | && || e1?e2:e3 = *= /= Scope resolution Global Array subscript Function call Conversion None Member selection (object) Member selection (pointer) Postfix increment Postfix decrement Allocate object Deallocate object Deallocate object Prefix increment Prefix decrement Dereference Address-of Unary plus Arithmetic negation (unary) Logical NOT Bitwise complement Size of object Size of type type name Type cast (conversion) Type cast (conversion) Type cast (conversion) Type cast (conversion) Type cast (conversion) Apply pointer to class member (objects) Dereference pointer to class member Multiplication Division Remainder (modulus) Addition Subtraction Left shift Right shift Less than Greater than Less than or equal to Greater than or equal to Equality Inequality Bitwise AND Bitwise exclusive OR Bitwise OR Logical AND Logical OR Conditional Assignment Multiplication assignment Division assignment None None Left to right Left to right Left to right Left to right None None None None None None None None None None None None None None None None Right to left None None None None Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Right to left Right to left .

c) New operators introduced: new. # . return 0.txt". _getch().3 Write a program which decreasingly sorts a set of words. b) except for the following ones: . } 4.* . 4. FILE* fp=fopen("test.1 Print on the screen a text from a txt file “test. Problems 4. . return 0. For each operation define a separate function. Modulus assignment Addition assignment Subtraction assignment Left-shift assignment Right-shift assignment Bitwise AND assignment Bitwise inclusive OR assignment Bitwise exclusive OR assignment Comma Lab 2 C++ Right to left Right to left Right to left Right to left Right to left Right to left Right to left Right to left Left to right Remarks: a) Operators can be oveloaded. :: . fclose(fp). . "r"). if(fp==NULL) { cout<<"Error when trying to open the text file" <<endl. . .*. ? : . ->. The user introduces the words.Incompatibilities / Differences between C and C++ %= += -= <<= >>= &= |= ^= . ##. delete. } while((ch=fgetc(fp))!=EOF) cout<<ch.txt” int main() { //system("color fc"). char ch.2 Search how many times a word (introduced by the user) occurs in a text file. 4.*.