360 likes | 482 Views
C & C++. High School/ Jr.High 10 PRINT "HELLO WORLD" 20 END Prints “HELLO WORLD”. First year in College program Hello(input , output) begin writeln('Hello World') end. Prints “HELLO WORLD”. Senior year in College ( defun hello (print
E N D
High School/Jr.High 10 PRINT "HELLO WORLD" 20 END Prints “HELLO WORLD”
First year in College program Hello(input, output) begin writeln('Hello World') end. Prints “HELLO WORLD”
Senior year in College (defun hello (print (cons 'Hello (list 'World)))) Prints “HELLO WORLD”
New professional #include <stdio.h> void main(void) { char *message[] = {"Hello ", "World"}; inti; for(i = 0; i < 2; ++i) printf("%s", message[i]); printf("\n"); } Prints “HELLO WORLD”
Seasoned professional #include <iostream.h> #include <string.h> class string { private: int size; char *ptr; string() : size(0), ptr(new char[1]) { ptr[0] = 0; } string(const string &s) : size(s.size) { ptr = new char[size + 1]; strcpy(ptr, s.ptr); } ~string() { delete [] ptr; } friend ostream &operator <<(ostream &, const string &); string &operator=(const char *); }; ostream &operator<<(ostream &stream, const string &s) { return(stream << s.ptr); } string &string::operator=(const char *chrs) { if (this != &chrs) { delete [] ptr; size = strlen(chrs); ptr = new char[size + 1]; strcpy(ptr, chrs); } return(*this); } int main() { string str; str = "Hello World"; cout << str << endl; return(0); } Prints “HELLO WORLD”
Master Programmer [ uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820) ] library LHello { // bring in the master library importlib("actimp.tlb"); importlib("actexp.tlb"); // bring in my interfaces #include "pshlo.idl” [ uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820) ] cotypeTHello { interface IHello; interface IPersistFile; }; }; [ exe, uuid(2573F890-CFEE-101A-9A9F-00AA00342820) ] module CHelloLib { // some code related header files importheader(<windows.h>); importheader(<ole2.h>); importheader(<except.hxx>); importheader("pshlo.h"); importheader("shlo.hxx"); importheader("mycls.hxx"); // needed typelibs importlib("actimp.tlb"); importlib("actexp.tlb"); importlib("thlo.tlb"); [ uuid(2573F891-CFEE-101A-9A9F-00AA00342820), aggregatable ] coclassCHello { cotypeTHello; }; }; #include "ipfix.hxx” extern HANDLE hEvent; class CHello : public CHelloBase { public: IPFIX(CLSID_CHello); CHello(IUnknown *pUnk); ~CHello(); HRESULT __stdcallPrintSz(LPWSTRpwszString); private: static intcObjRef; }; #include <windows.h> #include <ole2.h> #include <stdio.h> #include <stdlib.h> #include "thlo.h" #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx” intCHello::cObjRef = 0; CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk) { cObjRef++; return; } HRESULT __stdcallCHello::PrintSz(LPWSTRpwszString) { printf("%ws ", pwszString); return(ResultFromScode(S_OK)); } CHello::~CHello(void) { // when the object count goes to zero, stop the server cObjRef--; if( cObjRef == 0 ) PulseEvent(hEvent); return; } #include <windows.h> #include <ole2.h> #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx” HANDLE hEvent; int _cdecl main( intargc, char * argv[] ) { ULONG ulRef; DWORD dwRegistration; CHelloCF *pCF = new CHelloCF(); hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); // Initialize the OLE libraries CoInitializeEx(NULL, COINIT_MULTITHREADED); CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegistration); // wait on an event to stop WaitForSingleObject(hEvent, INFINITE); // revoke and release the class object CoRevokeClassObject(dwRegistration); ulRef = pCF->Release(); // Tell OLE we are going away. CoUninitialize(); return(0); } extern CLSID CLSID_CHello; extern UUID LIBID_CHelloLib; CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */ 0x2573F891, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */ 0x2573F890, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; #include <windows.h> #include <ole2.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "pshlo.h" #include "shlo.hxx" #include "clsid.h” int _cdecl main( intargc, char * argv[] ) { HRESULT hRslt; IHello *pHello; ULONG ulCnt; IMoniker * pmk; WCHAR wcsT[_MAX_PATH]; WCHAR wcsPath[2 * _MAX_PATH]; // get object path wcsPath[0] = '\0'; wcsT[0] = '\0'; if( argc > 1) { mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1); wcsupr(wcsPath); } else { fprintf(stderr, "Object path must be specified\n"); return(1); } // get print string if(argc > 2) mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1); else wcscpy(wcsT, L"Hello World"); printf("Linking to object %ws\n", wcsPath); printf("Text String %ws\n", wcsT); // Initialize the OLE libraries hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(SUCCEEDED(hRslt)) { hRslt = CreateFileMoniker(wcsPath, &pmk); if(SUCCEEDED(hRslt)) hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello); if(SUCCEEDED(hRslt)) { // print a string out pHello->PrintSz(wcsT); Sleep(2000); ulCnt = pHello->Release(); } else printf("Failure to connect, status: %lx", hRslt); // Tell OLE we are going away. CoUninitialize(); } return(0); } Prints “HELLO WORLD”
C and C++ are higher-level languages that are designed to be independent of computational platform • Higher-level languages must be translated into the low-level machine language in order to run. • This is done via compiler and yields an executable specific to that platform
Differences between C & C++ • C++ grew out of C and is mostly a superset of the latter, but it is considered a different language • They are not developed to be cross-compatible & C++ does not supersede the use of C • C++ introduces many features that are not available in C and in practice almost all code written in C++ is not valid C code • There are many C syntaxes which are invalid or behave differently in C++
Basics of C • Simple C programs have the following structure • Comments • Library inclusions • Main Program • C programs should end in .c ; C++ in .cpp Lecture based largely on : http://www.physics.drexel.edu/students/courses/Comp_Phys/General/C_basics/
Comment blocks • /* …. */ : Used to enclose comments /* * File: hello.c * --------------- * This program prints the message “Hello, world.” */ • Unlike other languages covered to date, there is no need to tell the machine what language the text file is in (no #!/bin/c for example)
Libraries • Libraries are collections of tools written by other programmers that perform specific operations • They are much more important to C than previous languages we have studied. You have to declare at least the stdlib.h for a program to compile. #include <stdio.h>the standard input/output library #include <stdlib.h> the standard general purpose library #include <math.h> the standard math library #include “hrdfavorites.h”a personal extended library
Main Program • This block contains the program itself main() { printf(“Hello.\n”); } • Officially, we are defining a function called main with the body of the function contained in {}
Variables • Variables need to be declared in C/C++ !!! • numeric variable types include: • int: integers • short: short integers • long: long integers (more memory) • float: single-precision real floating point number • double: double-precision real floating point (more precision but also more memory) • string variable types include • char: character variable (1 byte)
Declaring variables • Here are some examples of variable declaration main() { inta,b,c; double dd,ee,ff; } • Variables should be declared at the beginning of your program.
There is no special syntax ($, @) for a variable once it has been declared. #include < stdio.h> #include < math.h> main() { intangle_degree; double angle_radian, pi, value; printf ("\nCompute a table of the sine function\n\n");
/* obtain pi once for all */ /* or just use pi = M_PI, where M_PI is defined in math.h */ pi = 4.0*atan(1.0); printf ( " Value of PI = %f \n\n", pi ); printf ( " angle Sine \n" ); angle_degree=0; /* initial angle value */ while ( angle_degree <= 360 ) { /* loop until angle_degree > 360 */ angle_radian = pi * angle_degree/180.0 ; value = sin(angle_radian); printf ( " %3d %f \n ", angle_degree, value ); angle_degree = angle_degree + 10; /* increment the loop index */ } }
Floats/doubles are relatively easy to use but problems tend to occur when performing division. • An int divided by an int returns an int. • An int divided by a float returns a float. • A float divided by an int returns a float. • A float divided by a float returns a float. • As an example, 3 is considered as an int, but 3.0 is considered as a float. • If you want to store the result of a division as a floating-point (decimal) number, make sure you store it in a float declared variable.
Explicit conversion • you can specify explicit conversion by using a type cast int num, den; double quotient; quotient = num / (double) den; /*this recasts den as a double so the value of an int/double is a double.
Global Constants • You can define constants of any type by using the #define compiler directive. Its syntax is simple--for instance #define ANGLE_MIN 0 #define ANGLE_MAX 360 • C distinguishes between lowercase and uppercase letters in variable names. It is customary to use capital letters in defining global constants. • These are traditional declared after the #include calls
Loops • C is the original looping language…love it or hate it • Statement blocks, or a sequences of statements, are encased using { }. • Statements are executed in sequence from first to last by default. { first_statement; last_statement; }
while • while: continues to loop as long as condition exited successfully count = 0; while (count < 10) { count += 2; printf ("count is now %d\n”,count); } • There is no print, there is only printf. • You have to initial numeric variables to 0 to avoid getting unknown machine start values
if/else if/else • If expression is true, then run the first set of commands. Else if a second expression is true, run the second set of commands. Else if neither is true, run a third set of commands. End the if command if ( a > b) { statement } else if (a == b){ statement } else { printf ”%d is less than %d.\n”, a, b; }
Conditional Operators • Conditionals are logical operations involving comparison of quantities (of the same type) using the conditional operators: < greater than <= greater than or equal to == equal to != not equal to >= greater than or equal to > greater than • and the boolean operators && and || or ! not
for • one of the most common loop structures is the for loop, which iterates over an array of objects • fori values in array, do this for(i=0; i<=10; i++ ) { for (j=0; j<=10; j++) { H[i][j]=0; } }
switch • The appropriate block of statements is executed according to the value of the expression, compared with the constant expressions in the case statement. • This construct is particularly useful in handling input variables. switch (n) { case 1: printf(“Ace\n”); break; case 11: { /*there is some flexibility in syntax*/ printf(“Jack\n”); break; } ….. default: printf (“%d\n”,n); break; }
break • break: allows you to break out of a for, do, while, or switch loop • Default behavior is the break out of the enclosing loop for ( a=0; a<20; a++ ) { if ( a > 10) { break; } } ## last comes here ##
Arrays • Arrays of any type can be formed in C. The syntax is simple: type name[dim]; double name[100][50]; /*you have to already know how big the array/vector will be!*/ • In C, arrays start at position 0. • The elements of the array occupy adjacent locations in memory.
Pointers • The C language allows the programmer to ``peek and poke'' directly into memory locations. This gives great flexibility and power to the language, but it also one of the great hurdles that the beginner must overcome in using the language. • the variables called pointers store the address of other variables. int *p; /*declared that p is a pointer*/ p=&x; /*p is the address of x */ *p = 17; /* same as setting x = 17 */
Strings • You have to think of strings as character vectors (much like matlab) • Strings are manipulated either via pointers or via special routines available from the standard string library string.h. • #include <string.h> to work efficiently with strings char string[20]; char message[] = “Hello, world.”;
main() { char text_2[100]; char *ta, *tb; int I; /* set message to be an array of characters; initialize it to the constant string "...” and * let the compiler decide its size by using [] */ char message[] = "Hello, I am a string; what are you?”; printf("Original message: %s\n", message);
/* use explicit pointer arithmetic to copy the original message to text_2 */ ta=message; tb=text_2; while ( ( *tb++ = *ta++ ) != '\0' ) { ; } /*set the pointers equal at each element until FALSE (aka ! 0) */ printf("Text_2: %s\n", text_2); }
Higher-Level I/O • To read in from external files main(intargc, char **argv) { const char *progname = argv[0]; if (argc==5) { /*argc = number command line files listed*/ sscanf(argv[1], "%s", cfile); /*argv stores the files/values*/ sscanf(argv[2], "%s", sfile); sscanf(argv[3], "%d", &winlen); sscanf(argv[4], "%f", &thresh); } fl=fopen("outdesc","w"); fc=fopen(cfile,"r"); • Here, fl and fc are file handles. If you include stdio.h, you would declare them as FILE *fl, *fc;
#include < stdio.h> void main() { FILE *fp; inti; fp = fopen("foo.dat", "w"); /* open foo.dat for writing */ fprintf(fp, "\nSample Code\n\n"); /* write some info */ for (i = 1; i <= 10 ; i++) fprintf(fp, "i = %d\n", i); fclose(fp); /* close the file */ }
Subroutines • A function has the following layout: return-type function-name ( argument-list-if-necessary ) { ...local-declarations... ...statements... return return-value; } • If return-type is omitted, C defaults to int.
intn_char(char string[]) { int n; /* local variable in this function */ /* strlen(a) returns the length of string a */ /* defined via the string.h header */ n = strlen(string); if (n > 50) printf("String is longer than 50 characters\n"); return n; /* return the value of integer n */ }