Transcript C vs C++

C vs C++

Natalie Linnell

C++ is built on C, so..

• • • Most stuff is the same!

Most of the ways they’re different are things that you CAN do in C++ that you can’t do in C Mostly, C++ is better.  – Except that C is faster

• • •

Things that are different

Cout, cin, file I/O is done differently – This is the biggie No classes/objects in C No call by reference in C – Get around this using pointers, which you’ll learn about in CS60.

• Little stuff – No bool type, no keywords true, false • CAN have (x<6) which evaluates to 0 (false) or 1 (true).

– No // comments – No namespaces – No int x(0); – No static_cast(x); • Just use (double)x – etc

Equivalents of cout<< and cin>>

• There are no streams in C. Instead, you use functions from #include – Cout<<“Hello world”<>a; – Scanf(“%d”, a); – See the code for more details

File I/O

Little stuff

Strings

– There are no STL strings – You MUST use c strings • char str[10] = “hello!”; • Remember the \0 is there.

More little stuff

• #includes are different – In C: • #include • #include – In C++: • #include //New libraries that weren’t in C • #include //Libraries that were in C lose the .h and get a c in front • #include

More little stuff

• Structs are a little different – You need to add the word typedef in front typedef struct Date{ int day; int month; int year; }; Now you can use it like you would in C++ Otherwise if you leave off the typedef, when you’re declaring a Date variable you need to do struct Date d1;

More little stuff

• • • Declaring variables Variables must be declared at the beginning of a function and must be declared before any other code. This includes loop counter variables, which means you can't do this: for(i = 0; i < 200; i++)

More little stuff

• Constants – #define MAX_LEN 1024 – #defines usually appear right after the #includes.

Stuff not in C that you won’t get to until 60

• • • No new and delete; must use malloc and free No function overloading or default parameter values No call by reference, but you get around this by using pointer parameters, which you’ll learn about in CS60.

Write a recursive C++ function int EvenSum(int n) to compute 2 + 4 + … + 2n. Write a program that counts the number of words in the file in.txt A word is defined to be a consecutive block of characters that does not contain a space, a tab, or a carriage return. For example, the word count(" isn't this easy ? ") is 4.