Example: confidence

C for Java Programmers

C for Java ProgrammersGeorge FergusonSummer 2016(Updated Summer 2021)2 Contents1 Introduction72 Overview of Java and s The Same? .. s Different? .. 103 Development and and Execution in Java and C .. Up Your Development Environment .. Your First C Program .. Your First C Program .. 174 Basic Expressions and .. Types .. Output .. and Expressions .. and Assigment .. 2934 CONTENTS5 Control Statements .. Statements .. Control Flow Statements .. 336 Parameters and Arguments .. Declarations .. 377 Structured Types398 Memory , Addresses, and Pointers .. Arguments by Reference .. Allocation .. Memory Allocation in Java .. Memory Allocation in C .. Arrays .. Data Structures .. Pointers .. 649 Defining New Types6910 Sharing code : Files and The C Preprocessor .. Separate Compilation, Libraries, and Linking.

object code. Although it is technically possible to run just one or the other phase of the C compiler, you will never do that in practice. •Before your code can be run, it needs to be “linked” with any libraries that it uses, including the C runtime. The result is an executable file containing native object code.

Tags:

  Code, Executable

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of C for Java Programmers

1 C for Java ProgrammersGeorge FergusonSummer 2016(Updated Summer 2021)2 Contents1 Introduction72 Overview of Java and s The Same? .. s Different? .. 103 Development and and Execution in Java and C .. Up Your Development Environment .. Your First C Program .. Your First C Program .. 174 Basic Expressions and .. Types .. Output .. and Expressions .. and Assigment .. 2934 CONTENTS5 Control Statements .. Statements .. Control Flow Statements .. 336 Parameters and Arguments .. Declarations .. 377 Structured Types398 Memory , Addresses, and Pointers .. Arguments by Reference .. Allocation .. Memory Allocation in Java .. Memory Allocation in C .. Arrays .. Data Structures .. Pointers .. 649 Defining New Types6910 Sharing code : Files and The C Preprocessor .. Separate Compilation, Libraries, and Linking.

2 Standard System Libraries .. Project Development .. Building Larger C Programs .. 7911 Debugging a C Debuggers .. Compiler Options .. valgrind .. 8512 Final Thoughts8713 References896 CONTENTSC hapter 1 IntroductionWhen I teach introductory programming, I tell students that they are learning aforeign language: the language understood by the computer. The purpose of pro-gramming is to translate your ideas about how to solve a problem into a languagethat the computer understands so that it can follow your are a Java programmer. You are already fluent in the Java programminglanguage. But now you find that you need to learn a new programming language,a language called C. This is just like learning a second (human) I m sure you know, some human languages are more similar than others. Ifyou know Spanish, you can learn French or Italian relatively easily. Many of theconstructions are the same, although there are some important differences in thedetails.

3 On the other hand, if you know English, it s of relatively little use to youin learning Chinese or Japanese they don t even use the same characters!Luckily for you, Java and C are closely related. In fact, Java was developed bystarting with C and adding features designed to help Programmers develop com-plex programs more quickly and with fewer errors. Thus you will have no problemunderstanding the high-level structure of a C program. There are important dif-ferences that we will point out, starting in the next sections, but it really is a fairlyeasy 1. INTRODUCTIONKeep in mind as you learn C that you are stepping back in the history of program-ming. C was developed in the early 1970 s when computers were much simpler(and less powerful) than today. Java appeared in the mid-1990 s and has beenevolving and expanding ever since. A fundamental thing to realize is that C pro-videsmuch less supportto the programmer. It ismucheasier to make mistakesandvery oftenharder to figure out how to fix them.

4 It requires somedisciplinetouse correctly and why would anyone use C? There are a couple of reasons. First, because asyou will see in Section 3, a C program runs in a much smaller memory makes C the choice for embedded systems and other environments wherememory is at a premium. Second, because C programs run with less support, theymay also run faster. Although higher-level languages like Java and C# have gottenfaster, it is still probably the case that tightly coded C is as fast as you can getwithout writing assembly code , which is not only much harder but by definitionnot portable across platforms. If speed is important, C is often the reason to use C is that it is kind of the universal interchange language. Manyother languages interoperate with C, allowing you to connect components writtenin different languages into one application using C. Finally, because C is moreminimalist than many of its successors, it forces the programmer to confront someilluminating design and implementation questions and really think about whattheir code is note that this guide is not a definitive manual for the C programming lan-guage.

5 For that, you should get a copy ofThe C Programming Language, SecondEditionby Brian Kernighan and Dennis Ritchie. I will refer to this as K&R inthe rest of this document. Not only is it the definitive specification of the language,it s one of the clearest, most useful books you will ever read. You will learn thingsabout programming and programming languages that you can apply to any lan-guage, including Java. Knowing C will make you a better Java programmer, aswell as having an additional very useful tool in your programming the flip side, for many, possibly even most, programs, speed isnotthat important, andcertainly much less important than 2 Overview of Java and CLet s start with a quick overview of the similarities and differences between Javaand What s The Same?Since Java is derived from C, you will find many things that are familiar: Values, types (more or less), literals, expressions Variables (more or less) Conditionals:if,switch Iteration:while,for,do-while, but notfor-in-collection ( colon syntax) Call-return (methods in Java, functions in C): parameters/arguments, returnvalues Arrays (with one big difference) Primitive and reference types Typecasts Libraries that extend the core language (although the mechanisms differsomewhat)910 CHAPTER 2.

6 OVERVIEW OF JAVA AND What s Different?On the other hand, C differs from Java in some important ways. This section givesyou a quick heads-up on the most important of these. No classes or objects: C is not an object-oriented language, although it hasstructured types (structandunion) and there are ways of doing thingslike inheritance, abstraction, and composition. C also has a mechanism forextending its type system (typedef). Arrays are simpler: there is no bounds checking (your program just dies ifyou access a bad index), and arrays don t even know their own size! Strings are much more limited, although the C standard library helps. No collections (lists, hashtables,etc.), exceptions, or generics. No memory management: You must explicitly allocate (malloc) and re-lease (free) memory to use dynamic data structures like lists, trees, andso on. C does almost nothing to prevent you from messing up the memoryused by your is the number one cause of problems for new(and old) C Programmers .

7 Pointer arithmetic: You can, and often have to, use addresses of items inmemory (called pointers). C allows you to change the contents of memoryalmost arbitrarily. This is powerful but also dangerous line: When you program in C you are closer to the machine. This givesyou more flexibility but less protection. The next section explains this in moredetail by comparing the development and execution models of Java and 3 Development and Development and Execution in Java and CFigure (page 12) shows the basic components involving in developing andexecuting a Java program. You should already be familiar with this process, so Iwill describe it only briefly. You write your program (source code ) as a text file using the Java program-ming language. The name of your source file ends in .java . You compile your source code using thejavaccommand ( Java com-piler ) to create a Java class file containing bytecode (.classfile). Bytecode does not use the native instruction set of any real computer.

8 In-stead, it uses an abstract instruction set designed for an abstract computercalled the Java Virtual Machine or JVM. To run your program, you run thejavacommand, which simulates theJVM running on your actual computer. You tell it to load and run your classfile (bytecode), which results in your code being executed. That is, you have a real program,java, running on your computer, andit is simulating the execution of the bytecode of your program on the not-real JVM. This is slower than running native code directly on the computer,but also safer and better for development. Java programs can use other classes and libraries of other classes (jars) toprovide additional functionality. In fact, most of Java is library 3. DEVELOPMENT AND interpret compile run compile tonative code sourcecodebytecodeexecutablelibrariesFig ure : Java Development and Execution . link preprocess run ldexecutablesourcecodeobjectcodelibrarie scc compile Figure : C Development and Execution DEVELOPMENT AND EXECUTION IN JAVA AND C13 To partially compensate for the slowdown due to interpreting bytecode, Javaincludes a feature called a Just In Time or JIT compiler.

9 This part ofthejavaruntime system detects pieces of Java code that are executed fre-quently and compiles them into the real instruction set of the host computer(native code ). This is faster than interpreted bytecode, but usually not quiteas fast a native code . Finally, note that the Java compiler,javac, is itself a Java program, writtenin Java! That is, runningjavacmeans runningjava(the Java runtime)and telling it to run the class for the Java compiler. I ll let you think abouthow the first Java compiler was written..By comparison, Figure shows a similar component diagram for developmentand execution in C. I ll point out the main differences briefly. In C, you write your program as a text file using the C programming lan-guage. The name of your source file ends in .c . You then compile your code into processor-specific object code ( .o ) us-ing thecccommand (for C compiler ). The C compiler actually consists of two phases. The first is a pre-processing phase which can transform the text of your program in various useful the compiler phase translates the resulting C program text into nativeobject code .

10 Although it is technically possible to run just one or the otherphase of the C compiler, you will never do that in practice. Before your code can be run, it needs to be linked with any libraries thatit uses, including the C runtime. The result is an executable file containingnative object code . You can run your executable directly from the command line. If it crashes,your program dies. Sometimes this happens without even a message unlessyou are using a debugger. In the not-so-good old days, you might even crashthe entire machine. A compiled C program runs at full speed on the processor for which it 3. DEVELOPMENT AND EXECUTIONIn general, the key difference between Java and C is that in C you are runningmuch closer to the machine. When computers were less powerful and had lessmemory, it was vital to squeeze out every drop of performance in order to doeven simple computing tasks. The history of programming languages is a contin-ual evolution from low-level object code and assembly language to higher-levellanguages like Fortran, Algol, Lisp, Smalltalk, Java, Javascript, and all the othermodern languages.


Related search queries