C Programming

Total Page:16

File Type:pdf, Size:1020Kb

C Programming C PROGRAMMING 6996 Columbia Gateway Drive Suite 100 Columbia, MD 21046 Tel: 443-692-6600 http://www.umbctraining.com C PROGRAMMING Course # TCPRG3000 Rev. 10/14/2016 ©2016 UMBC Training Centers 1 C PROGRAMMING This Page Intentionally Left Blank ©2016 UMBC Training Centers 2 C PROGRAMMING Course Objectives ● At the conclusion of this course, students will be able to: ⏵ Write non-trivial C programs. ⏵ Use data types appropriate to specific programming problems. ⏵ Utilize the modular features of the C languages. ⏵ Demonstrate efficiency and readability. ⏵ Use the various control flow constructs. ⏵ Create and traverse arrays. ⏵ Utilize pointers to efficiently solve problems. ⏵ Create and use structures to implement new data types. ⏵ Use functions from the C runtime library. ©2016 UMBC Training Centers 3 C PROGRAMMING This Page Intentionally Left Blank ©2016 UMBC Training Centers 4 C PROGRAMMING Table of Contents Chapter 1: Getting Started..............................................................................................9 What is C?..................................................................................................................10 Sample Program.........................................................................................................11 Components of a C Program......................................................................................13 Data Types.................................................................................................................14 Variables.....................................................................................................................16 Printing and Initializing Variables...............................................................................17 Arrays.........................................................................................................................19 Compiling and Executing a C Program......................................................................21 Chapter 2: Functions and Operators...........................................................................25 Functions....................................................................................................................26 Elementary Operators................................................................................................28 Assignment Operators................................................................................................29 Increment and Decrement Operators.........................................................................30 Number of Operands..................................................................................................32 Conditional Operator..................................................................................................33 Chapter 3: Control Flow Constructs............................................................................39 Conditionals................................................................................................................40 if..................................................................................................................................41 if-else-if.......................................................................................................................43 switch..........................................................................................................................45 Loops..........................................................................................................................46 while............................................................................................................................47 for................................................................................................................................48 do-while......................................................................................................................49 Endless Loops............................................................................................................50 break and continue.....................................................................................................51 switch..........................................................................................................................53 Chapter 4: The C Preprocessor....................................................................................61 #define........................................................................................................................62 Preprocessor Macros.................................................................................................64 #include......................................................................................................................66 Conditional Compilation.............................................................................................67 #ifndef.........................................................................................................................69 Chapter 5: Simple I/O.....................................................................................................73 Character I/O..............................................................................................................74 End of File..................................................................................................................76 Simple I/O Examples..................................................................................................78 Simple I/O Redirection...............................................................................................80 I/O with Character Arrays...........................................................................................81 ©2016 UMBC Training Centers 5 C PROGRAMMING Chapter 6: More on Functions......................................................................................85 Introduction.................................................................................................................86 Function Declarations.................................................................................................87 Returning a Value or Not............................................................................................88 Function Prototypes...................................................................................................89 Arguments and Parameters.......................................................................................91 Organization of C Source Files..................................................................................93 Extended Example.....................................................................................................94 The getaline Function.................................................................................................96 The mystrcmp Function..............................................................................................97 The check Function....................................................................................................98 The myatoi Function...................................................................................................99 The average Function..............................................................................................100 Summary..................................................................................................................101 Chapter 7: Strings........................................................................................................105 Fundamental Concepts............................................................................................106 Aggregate Operations..............................................................................................108 String Functions........................................................................................................110 String Functions Example........................................................................................112 Chapter 8: Pointers......................................................................................................115 Fundamental Concepts............................................................................................116 Pointer Operators and Operations...........................................................................118 Changing an Argument with a Function Call............................................................119 Pointer Arithmetic.....................................................................................................121 Array Traversal.........................................................................................................123 String Functions with Pointers..................................................................................127 Pointer Difference.....................................................................................................129 Prototypes for String Functions................................................................................130 Relationship Between an Array and a Pointer.........................................................131 The Pointer Notation *p++........................................................................................132 Chapter 9: Structures..................................................................................................137 Fundamental
Recommended publications
  • What Are the Problems with Embedded Linux?
    What Are the Problems with Embedded Linux? Every Operating System Has Benefits and Drawbacks Linux is ubiquitous. It runs most internet servers, is inside Android* smartphones, and is used on millions of embedded systems that, in the past, ran Real-Time Operating Systems (RTOSes). Linux can (and should) be used were possible for embedded projects, but while it gives you extreme choice, it also presents the risk of extreme complexity. What, then, are the trade-offs between embedded Linux and an RTOS? In this article, we cover some key considerations when evaluating Linux for a new development: ■ Design your system architecture first ■ What is Linux? ■ Linux vs. RTOSes ■ Free software is about liberty—not price ■ How much does Embedded Linux cost? ■ Why pay for Embedded Linux? ■ Should you buy Embedded Linux or roll-your-own (RYO)? ■ To fork or not to fork? ■ Software patching ■ Open source licensing ■ Making an informed decision The important thing is not whether Linux or an RTOS is “the best,” but whether either operating system—or both together—makes the most technical and financial sense for your project. We hope this article helps you make an informed decision. Design Your System Architecture First It is important to design your system architecture first—before choosing either Linux or an RTOS—because both choices can limit architectural freedom. You may discover that aspects of your design require neither Linux nor an RTOS, making your design a strong candidate for a heterogeneous approach that includes one or more bare-metal environments (with possibly a Linux and/or RTOS environment as well).
    [Show full text]
  • C Programming Language Review
    C Programming Language Review Embedded Systems 1 C: A High-Level Language Gives symbolic names to values – don’t need to know which register or memory location Provides abstraction of underlying hardware – operations do not depend on instruction set – example: can write “a = b * c”, even if CPU doesn’t have a multiply instruction Provides expressiveness – use meaningful symbols that convey meaning – simple expressions for common control patterns (if-then-else) Enhances code readability Safeguards against bugs – can enforce rules or conditions at compile-time or run-time Embedded Systems 2 A C Code “Project” • You will use an “Integrated Development Environment” (IDE) to develop, compile, load, and debug your code. • Your entire code package is called a project. Often you create several files to spilt the functionality: – Several C files – Several include (.h) files – Maybe some assembly language (.a30) files – Maybe some assembly language include (.inc) files • A lab, like “Lab7”, will be your project. You may have three .c, three .h, one .a30, and one .inc files. • More will be discussed in a later set of notes. Embedded Systems 3 Compiling a C Program C Source and Entire mechanism is usually called Header Files the “compiler” Preprocessor – macro substitution C Preprocessor – conditional compilation – “source-level” transformations • output is still C Compiler Source Code Compiler Analysis – generates object file Symbol Table Target Code • machine instructions Synthesis Linker – combine object files Library (including libraries) Linker into executable image Object Files Executable Image Embedded Systems 4 Compiler Source Code Analysis – “front end” – parses programs to identify its pieces • variables, expressions, statements, functions, etc.
    [Show full text]
  • Section “Common Predefined Macros” in the C Preprocessor
    The C Preprocessor For gcc version 12.0.0 (pre-release) (GCC) Richard M. Stallman, Zachary Weinberg Copyright c 1987-2021 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation. A copy of the license is included in the section entitled \GNU Free Documentation License". This manual contains no Invariant Sections. The Front-Cover Texts are (a) (see below), and the Back-Cover Texts are (b) (see below). (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development. i Table of Contents 1 Overview :::::::::::::::::::::::::::::::::::::::: 1 1.1 Character sets:::::::::::::::::::::::::::::::::::::::::::::::::: 1 1.2 Initial processing ::::::::::::::::::::::::::::::::::::::::::::::: 2 1.3 Tokenization ::::::::::::::::::::::::::::::::::::::::::::::::::: 4 1.4 The preprocessing language :::::::::::::::::::::::::::::::::::: 6 2 Header Files::::::::::::::::::::::::::::::::::::: 7 2.1 Include Syntax ::::::::::::::::::::::::::::::::::::::::::::::::: 7 2.2 Include Operation :::::::::::::::::::::::::::::::::::::::::::::: 8 2.3 Search Path :::::::::::::::::::::::::::::::::::::::::::::::::::: 9 2.4 Once-Only Headers::::::::::::::::::::::::::::::::::::::::::::: 9 2.5 Alternatives to Wrapper #ifndef ::::::::::::::::::::::::::::::
    [Show full text]
  • C-Style Strings
    Introduction to printf and scanf A conceptual model of a C-string String handling functions in the C standard library String parsing functions Stuff to learn on your own C-Style Strings Mike Closson Dept of Computing Science University of Alberta Small modifications: Michael Buro Feb.2006 22nd February 2006 Mike Closson C-Style Strings Introduction to printf and scanf A conceptual model of a C-string String handling functions in the C standard library String parsing functions Stuff to learn on your own Introduction to printf, fprintf. Printing Strings: /* Print to standard output */ printf( "Hello, World!\n" ); /* Print to file associated with filepointer fp */ fprintf( fp, "Hello, World!\n" ); Mike Closson C-Style Strings Introduction to printf and scanf A conceptual model of a C-string String handling functions in the C standard library String parsing functions Stuff to learn on your own Flushing an I/O stream with fflush. For performance reasons, data written with the stream functions (fwrite, printf, fprintf) may not always appear on the terminal or file after the printf function returns. To force the data to be written, use the fflush function. printf("Enter your password: "); fflush( stdout ); Usually, fflush is not needed. Mike Closson C-Style Strings Introduction to printf and scanf A conceptual model of a C-string String handling functions in the C standard library String parsing functions Stuff to learn on your own Reading data with scanf. Data is written with printf, and data is read with scanf. char password[100]; printf( "Enter your password: " ); fflush( stdout ); if (scanf( "%99s", password ) != 1) // Error ..
    [Show full text]
  • Cheat Sheets of the C Standard Library
    Cheat Sheets of the C standard library Version 1.06 Last updated: 2012-11-28 About This document is a set of quick reference sheets (or ‘cheat sheets’) of the ANSI C standard library. It contains function and macro declarations in every header of the library, as well as notes about their usage. This document covers C++, but does not cover the C99 or C11 standard. A few non-ANSI-standard functions, if they are interesting enough, are also included. Style used in this document Function names, prototypes and their parameters are in monospace. Remarks of functions and parameters are marked italic and enclosed in ‘/*’ and ‘*/’ like C comments. Data types, whether they are built-in types or provided by the C standard library, are also marked in monospace. Types of parameters and return types are in bold. Type modifiers, like ‘const’ and ‘unsigned’, have smaller font sizes in order to save space. Macro constants are marked using proportional typeface, uppercase, and no italics, LIKE_THIS_ONE. One exception is L_tmpnum, which is the constant that uses lowercase letters. Example: int system ( const char * command ); /* system: The value returned depends on the running environment. Usually 0 when executing successfully. If command == NULL, system returns whether the command processor exists (0 if not). */ License Copyright © 2011 Kang-Che “Explorer” Sung (宋岡哲 <explorer09 @ gmail.com>) This work is licensed under the Creative Commons Attribution 3.0 Unported License. http://creativecommons.org/licenses/by/3.0/ . When copying and distributing this document, I advise you to keep this notice and the references section below with your copies, as a way to acknowledging all the sources I referenced.
    [Show full text]
  • SIPB's IAP Programming in C
    SIPB’s IAP Programming in C C was developed at AT&T Bell Labs between 1971 and 1973, by Dennis Ritchie. It was derived from an experimental language called B, which itself was a stripped-down version of BCPL. All of these are derivatives of the ALGOL family of languages, dating from the 1950s. This work was done on a PDP-11, a machine with a 16 bit address bus. While a PDP-11 should be able to address up to 64K of memory, these machines only had 24K. The C compiler was written in C, and was able to compile itself on these machines, running under the nascent Unix operating system. #include <stdio.h> main() The classic { printf("hello, world\n"); } /* * %% - a percent sign * %s - a string * %d - 32-bit integer, base 10 * %lld - 64-bit integer, base 10 * %x - 32-bit integer, base 16 * %llx - 64-bit integer, base 16 * %f, %e, %g - double precision * floating point number */ /* * the following should produce: A word on printf() * * printf() test: * string: 'string test' * number: 22 * float: 18.19 */ printf("printf() test:\n" " string: '%s'\n" " number: %d\n" " float: %g\n", "string test", 22, 18.19); Language Structure char i_8; There are five different /* -128 to 127 */ kinds of integer: unsigned char ui_8; /* 0 to 255 */ - char short i_16; - short /* -32768 to 32767 */ unsigned short ui_16; - int /* 0 to 65536 */ int i_32; - long /* -2147483648 to 2147483647 */ unsigned int ui_32; - long long /* 0 to 4294967295U */ long i_arch; unsigned ui_arch; Each of these can be /* architecture either: * dependent */ long long i64; - signed (the default)
    [Show full text]
  • Confine: Automated System Call Policy Generation for Container
    Confine: Automated System Call Policy Generation for Container Attack Surface Reduction Seyedhamed Ghavamnia Tapti Palit Azzedine Benameur Stony Brook University Stony Brook University Cloudhawk.io Michalis Polychronakis Stony Brook University Abstract The performance gains of containers, however, come to the Reducing the attack surface of the OS kernel is a promising expense of weaker isolation compared to VMs. Isolation be- defense-in-depth approach for mitigating the fragile isola- tween containers running on the same host is enforced purely in tion guarantees of container environments. In contrast to software by the underlying OS kernel. Therefore, adversaries hypervisor-based systems, malicious containers can exploit who have access to a container on a third-party host can exploit vulnerabilities in the underlying kernel to fully compromise kernel vulnerabilities to escalate their privileges and fully com- the host and all other containers running on it. Previous con- promise the host (and all the other containers running on it). tainer attack surface reduction efforts have relied on dynamic The trusted computing base in container environments analysis and training using realistic workloads to limit the essentially comprises the entire kernel, and thus all its set of system calls exposed to containers. These approaches, entry points become part of the attack surface exposed to however, do not capture exhaustively all the code that can potentially malicious containers. Despite the use of strict potentially be needed by future workloads or rare runtime software isolation mechanisms provided by the OS, such as conditions, and are thus not appropriate as a generic solution. capabilities [1] and namespaces [18], a malicious tenant can Aiming to provide a practical solution for the protection leverage kernel vulnerabilities to bypass them.
    [Show full text]
  • Tinyos Programming Philip Levis and David Gay Frontmatter More Information
    Cambridge University Press 978-0-521-89606-1 - TinyOS Programming Philip Levis and David Gay Frontmatter More information TinyOS Programming Do you need to know how to write systems, services, and applications using the TinyOS operating system? Learn how to write nesC code and efficient applications with this indispensable guide to TinyOS programming. Detailed examples show you how to write TinyOS code in full, from basic applications right up to new low-level systems and high-performance applications. Two leading figures in the development of TinyOS also explain the reasons behind many of the design decisions made and explain for the first time how nesC relates to and differs from other C dialects. Handy features such as a library of software design patterns, programming hints and tips, end-of-chapter exercises, and an appendix summarizing the basic application-level TinyOS APIs make this the ultimate guide to TinyOS for embedded systems programmers, developers, designers, and graduate students. Philip Levis is Assistant Professor of Computer Science and Electrical Engineering at Stanford University. A Fellow of the Microsoft Research Faculty, he is also Chair of the TinyOS Core Working Group and a Member of the TinyOS Network Protocol (net2), Simulation (sim), and Documentation (doc) Working Groups. David Gay joined Intel Research in Berkeley in 2001, where he has been a designer and the principal implementer of the nesC language, the C dialect used to implement the TinyOS sensor network operating system, and its applications. He has a diploma in Computer Science from the Swiss Federal Institute of Technology in Lausanne and a Ph.D.
    [Show full text]
  • A Type-Checking Preprocessor for Cilk 2, a Multithreaded C Language
    A Typechecking Prepro cessor for Cilk a Multithreaded C Language by Rob ert C Miller Submitted to the Department of Electrical Engineering and Computer Science in partial fulllment of the requirements for the degrees of Bachelor of Science in Computer Science and Engineering and Master of Engineering in Electrical Engineering and Computer Science at the Massachusetts Institute of Technology May Copyright Massachusetts Institute of Technology All rights reserved Author ::::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::: Department of Electrical Engineering and Computer Science May Certied by ::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::: Charles E Leiserson Thesis Sup ervisor Accepted by ::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::: F R Morgenthaler Chairman Department Committee on Graduate Theses A Typechecking Prepro cessor for Cilk a Multithreaded C Language by Rob ert C Miller Submitted to the Department of Electrical Engineering and Computer Science on May in partial fulllment of the requirements for the degrees of Bachelor of Science in Computer Science and Engineering and Master of Engineering in Electrical Engineering and Computer Science Abstract This thesis describ es the typechecking optimizing translator that translates Cilk a C ex tension language for multithreaded parallel programming into C The CilktoC translator is based on CtoC a to ol I developed that parses type checks analyzes and regenerates a C program With a translator based on CtoC
    [Show full text]
  • Nesc 1.2 Language Reference Manual
    nesC 1.2 Language Reference Manual David Gay, Philip Levis, David Culler, Eric Brewer August 2005 1 Introduction nesC is an extension to C [3] designed to embody the structuring concepts and execution model of TinyOS [2]. TinyOS is an event-driven operating system designed for sensor network nodes that have very limited resources (e.g., 8K bytes of program memory, 512 bytes of RAM). TinyOS has been reimplemented in nesC. This manual describes v1.2 of nesC, changes from v1.0 and v1.1 are summarised in Section 2. The basic concepts behind nesC are: • Separation of construction and composition: programs are built out of components, which are assembled (“wired”) to form whole programs. Components define two scopes, one for their specification (containing the names of their interfaces) and one for their implementation. Components have internal concurrency in the form of tasks. Threads of control may pass into a component through its interfaces. These threads are rooted either in a task or a hardware interrupt. • Specification of component behaviour in terms of set of interfaces. Interfaces may be provided or used by the component. The provided interfaces are intended to represent the functionality that the component provides to its user, the used interfaces represent the functionality the component needs to perform its job. • Interfaces are bidirectional: they specify a set of functions to be implemented by the inter- face’s provider (commands) and a set to be implemented by the interface’s user (events). This allows a single interface to represent a complex interaction between components (e.g., registration of interest in some event, followed by a callback when that event happens).
    [Show full text]
  • C Programming Tutorial
    C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i COPYRIGHT & DISCLAIMER NOTICE All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] ii Table of Contents C Language Overview .............................................................. 1 Facts about C ............................................................................................... 1 Why to use C ? ............................................................................................. 2 C Programs .................................................................................................. 2 C Environment Setup ............................................................... 3 Text Editor ................................................................................................... 3 The C Compiler ............................................................................................ 3 Installation on Unix/Linux ............................................................................
    [Show full text]
  • Choosing System C Library
    Choosing System C library Khem Raj Comcast Embedded Linux Conference Europe 2014 Düsseldorf Germany Introduction “God defined C standard library everything else is creation of man” Introduction • Standard library for C language • Provides primitives for OS service • Hosted/freestanding • String manipulations • Types • I/O • Memory • APIs Linux Implementations • GNU C library (glibc) • uClibc • eglibc – Now merged into glibc • Dietlibc • Klibc • Musl • bionic Multiple C library FAQs • Can I have multiple C libraries side by side ? • Can programs compiled with glibc run on uclibc or vice versa ? • Are they functional compatible ? • Do I need to choose one over other if I am doing real time Linux? • I have a baremetal application what libc options do I have ? Posix Compliance • Posix specifies more than ISO C • Varying degree of compliance What matters to you ? • Code Size • Functionality • Interoperability • Licensing • Backward Compatibility • Variety of architecture support • Dynamic Linking • Build system Codesize • Dietlibc/klibc – Used in really small setup e.g. initramfs • Bionic – Small linked into every process • uClibc – Configurable • Size can be really small at the expense of functionality • Eglibc – Has option groups can be ( < 1M ) License • Bionic – BSD/Apache-2.0 • Musl - MIT • Uclibc – LGPL-2.1 • Eglibc/Glibc – LGPL-2.1 Assigned to FSF • Dietlibc – GPLv2 • Klibc – GPLv2 • Newlib – some parts are GPLv3 Compliance • Musl strives for ISO/C and POSIX compliance No-mmu • uClibc supported No-mmu Distributions • Glibc is used in
    [Show full text]