C for C++ Programmers

Similar documents
CS3157: Advanced Programming. Outline

CS 261 Fall Mike Lam, Professor. Structs and I/O

C programming basics T3-1 -

CSCI 171 Chapter Outlines

Contents. A Review of C language. Visual C Visual C++ 6.0

Here's how you declare a function that returns a pointer to a character:

A Quick Look at C for C++ Programmers

Kurt Schmidt. October 30, 2018

PRINCIPLES OF OPERATING SYSTEMS

CSE 303: Concepts and Tools for Software Development

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Topic 6: A Quick Intro To C

CS 11 C track: lecture 5

File Access. FILE * fopen(const char *name, const char * mode);

20 Dynamic allocation of memory: malloc and calloc

C mini reference. 5 Binary numbers 12

Chapter 15 - C++ As A "Better C"

The Design of C: A Rational Reconstruction: Part 2

Continued from previous lecture

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CS349/SE382 A1 C Programming Tutorial

SWEN-250 Personal SE. Introduction to C

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

CSE 333 Midterm Exam July 24, Name UW ID#

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Programs in memory. The layout of memory is roughly:

Lectures 5-6: Introduction to C

Standard C Library Functions

This is CS50. Harvard University Fall Quiz 0 Answer Key

C Characters and Strings

Arrays, Strings, & Pointers

Short Notes of CS201

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

COP 3223 Final Review

CS201 - Introduction to Programming Glossary By

COP 3223 Final Review

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Fast Introduction to Object Oriented Programming and C++

Introduction to C++ (Extensions to C)

211: Computer Architecture Summer 2016

Should you know scanf and printf?

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Getting Started. Project 1

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

LAB 1: C PRIMER CS444/544 WENJIN HU JAN 16TH, 2009

Introduction to C++ Systems Programming

Lecture 03 Bits, Bytes and Data Types

Lectures 5-6: Introduction to C

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

printf( Please enter another number: ); scanf( %d, &num2);

Dynamic memory. EECS 211 Winter 2019

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

211: Computer Architecture Summer 2016

Intermediate Programming, Spring 2017*

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CS1003: Intro to CS, Summer 2008

THE UNIVERSITY OF WESTERN ONTARIO. COMPUTER SCIENCE 211a FINAL EXAMINATION 17 DECEMBER HOURS

Compiling and Running a C Program in Unix

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSE 333 Lecture 7 - final C details

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

Characters and Strings

Chapter 8 - Characters and Strings

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

Heap Arrays. Steven R. Bagley

CS 241 Data Organization Binary Trees

today cs3157-fall2002-sklar-lect05 1

CS 61c: Great Ideas in Computer Architecture

Chapter 8: Character & String. In this chapter, you ll learn about;

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

CSC231 C Tutorial Fall 2018 Introduction to C

C Basics And Concepts Input And Output

Personal SE. Functions, Arrays, Strings & Command Line Arguments

CSE 303: Concepts and Tools for Software Development

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Work relative to other classes

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

High Performance Programming Programming in C part 1

Transcription:

C for C++ Programmers CS230/330 - Operating Systems (Winter 2001). The good news is that C syntax is almost identical to that of C++. However, there are many things you're used to that aren't available in C: classes and all their associated tricks: templates, inheritance, etc. new and delete the stream operators << >> the // comment character the bool keyword all those weird casting operators (dynamic_cast, static_cast) the standard libraries you're used to (e.g. iostream) lots of other stuff We'll cover some of the basics here. I've also written up some linked list code both in C++ and C to give you a sense of the differences. The end of this document has a couple of recommended books where you can go for further information (including classic book on C written by Kernighan and Ritchie and referred to here as K&R). The man pages are also a great source of information. Comments The only valid way to specify a comment in C is like so: /* this is a comment */ /* This is a multiline comment */ You cannot nest comments. /* This is /*nested */ comment. And is illegal. */ I/O C doesn't have stream operators. Instead you'll want to use the functions provided in the stdio library. In particular: printf, fprintf, fgets, fputs. Output: printf, fprintf, fputs The most common output function in C is printf() which prints characters to the screen (or wherever standard out is directed to go).

Here's a quick hello world program that illustrates its use: #include <stdio.h> int main() { printf("hello World"); printf() has a variable number of arguments, the first of which is a format string. The format string can contain both ordinary characters (what you want to appear on the screen like 'Hello World' above) and conversion character sequences. You can think of conversion characters as placeholders for a specific type formatted in a particular way. Conversion character sequences begin with % and end with a conversion character. An example will perhaps make this clearer. Here we're printing out the integers from 0 to 9. int i; for (i = 0; i < 10; i++) { printf("the variable 'i' is: %d", i); The conversion sequence is %d, which you can think of as a placeholder for an integer. Since this is the first conversion character sequence, the value of the first argument after the format string--in this case the value of 'i'-- will be placed in the held spot. Conversion characters can specify type, precision, and all sorts of other formatting information. See K&R or the man pages for all the gory details, but here are essential ones cribbed from K&R: sequence type : produces %d or %i - int : signed decimal notation %s - char * : prints characters until the null character is reached %x - int : hexidecimal notation %p - void * : prints as a pointer printf() always prints to standard out. If you want to print to another place, such as standard error, use fprintf() which takes as its first argument the stream you're printing on: fprintf(stderr, "Fatal Error #2212. We're hosed"); /* or with values */ fprintf(stderr, "Fatal Error in foo(): value of bar is %p\n", bar); Note that we're calling standard in, out, and error slightly different names than we do in C++: C++ cin cout cerr C stdin stdout stderr Finally, fputs() will also allow us to write to a stream. int fputs(const char *str, FILE *stream);

fputs() takes a null-terminated string 'str' and writes it to 'stream'. It omits the null character when it does this. It returns a non-negative integer if okay and EOF on error. An example: if ( (fputs("hello world", stdout)) == EOF) { fprint(stderr, "Whoops, something went wrong"); fputs() functions similarly to printf() when it writes to stdout, but it doesn't do any conversion which probably means it's quite a bit faster. Input Input is a bit trickier. For reading an entire line you'll probably want to use fgets(). Here's the prototype: char *fgets(char *buffer, int size, FILE *stream); fgets() reads up to size-1 characters from stream and stores them in buffer. fgets() stores the null character ('\0') after the last character read into the buffer and returns 'buffer' if everything works fine, or NULL on error or end of file. Here's an example: char *cptr; char buffer[256]; printf("enter some stuff:\n"); cptr = fgets(buffer, 256, stdin); if(cptr!= NULL) { printf("you typed : %s\n", cptr); Here's a more complicated example. Readline() uses fgets() to read up to MAX_LINE - 1 characters into the buffer 'in'. It strips preceding whitespace and returns a pointer to the first non-whitespace character. char *Readline(char *in) { char *cptr; if (cptr = fgets(in, MAX_LINE, stdin)) { /* kill preceding whitespace but leave \n so we're guaranteed to have something*/ while(*cptr == ' ' *cptr == '\t') { cptr++; return cptr; else { return 0;

Memory Allocation There are no memory management operators such as new and delete in C. All memory allocation is done with the function malloc(). Here's its prototype: void * malloc(int nbytes) malloc() takes an int indicating the number of bytes you want allocated and it returns a void pointer to the start of the allocated memory. /* We're going to allocate enough space for an integer and assign 5 to that memory location */ int *foo; /* malloc call: note the cast of the return value from a void * to the appropriate pointer type */ foo = (int *) malloc(sizeof(int)); *foo = 5; Even more complicated structures like arrays are allocated through malloc(): /* Here we're allocating space for 5 integers */ int *foo; foo = (int *) malloc(sizeof(int) * 5); foo[0] = 17; foo[4] = 22; Freeing memory is done with the function free(). The prototype: void free(void *); Here's an example of it being used: free(foo); Pretty simple. However, note that it's disastrous to free a piece of memory that's already been freed. More information is available in the man pages. Variable Declaration In C++ you can declare variables pretty much anywhere in your program. This is not the case with C. 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(int i = 0; i < 200; i++) { Forgetting that you can't declare variables just anywhere is one of the most frequent causes of 'it won't compile' problems for programmers moving from C++ to C.

Constants The standard way to declare a constant in C is to use #define. #define MAX_LEN 1024 #define NUM_CALLS 20 This is also valid C++ code, though the use of #define is usually discouraged in C++. Like all preprocessor directives, #defines usually appear at the top of the source file. Types structs C has no classes, but you can create composite types with struct: struct point { int x; int y; ; You would then use it like so: struct point p; p.x = 0; p.y = 0; While this is acceptable, the preferred approach is to use pointers when using structures: struct point *p; p = (struct point *) malloc(sizeof(struct point)); p->x = 0; p->y = 0; The struct qualifier is required any time you're referring to a struct. You can see this above in the cast of the return value from malloc() and in the sizeof expression. In other words, having declared the struct point, we can't simply write: /* this code won't work */ point p; p.x = 0; as we would with a C++ class. We can get rid of this repetition of the struct qualifier by using typedefs. The typedef keyword essentially creates an alias. Thus we can typedef struct point to Point (or to lowercase 'point', but we're using uppercase to remind ourselves it's a struct).

typdef struct point Point; Point *p; p = (Point *) malloc(sizeof(point); p->x = 0; booleans There is no bool keyword in C. Instead booleans in C are the same as integers with a value of 0 for false or 1 for true. Thus the following is an infinite loop: while(1) { ; /* do nothing */ Libraries Libraries functions are included by specying the name of the appropriate header file in an include statement: #include <stdlib.h> #include <string.h> This is similar to C++ but the.h is required. Here are some of the most useful C libraries: stdio : printf, fprintf, sprintf, fgets, fputs string : strcpy, strcmp, strncmp, strtok, strlen stdlib : utility functions: atoi, atol, assert : useful in debugging: assert You should know what most of these functions do, especially strtok() which you'll be using at a crucial point in the Yash shell. Other References More information is available in the man pages and also in the best book on C: The C++ Programming Language by Kernighan and Ritchie (referred to as K&R by nearly everyone). Expert C Programming by Peter Van Der Linden is also an excellent book on all kinds of advanced C topics such as linking, the differences between pointers and arrays, and how to make sense of stuff like this: int *(*foo[20]) (char *c); It also has a pretty good description of program memory.

Example Linked List Code I've written some linked list code in both C++ and C to give you a sense of the differences. The C code has been heavily commented to reemphasize some of the information we just went over. You should be able to run either piece of code by saving it somewhere and compiling it: or: gcc -o llist llist.c g++ -o llist llist.cc I've also written a makefile that will compile both programs. Just save it to the same directory as the source files and type 'make' at the command prompt.