C Language Coding Standard

Similar documents
Introduction to C. CS2023 Winter 2004

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Chapter 11 Introduction to Programming in C

Programming. C++ Basics

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

Chapter 11 Introduction to Programming in C

Chapter 2, Part I Introduction to C Programming

Chapter 11 Introduction to Programming in C

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Program Organization and Comments

Pointers and scanf() Steven R. Bagley

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Programming and Data Structure

Procedures, Parameters, Values and Variables. Steven R. Bagley

Coding Standards for C

C Language, Token, Keywords, Constant, variable

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

CSE 374 Programming Concepts & Tools

Chapter 11 Introduction to Programming in C

Midterm Exam 2 Solutions C Programming Dr. Beeson, Spring 2009

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 1

Fundamentals of Programming Session 4

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

OBJECTIVE QUESTIONS: Choose the correct alternative:

CSCI 262 C++ Style Guide

In this session we will cover the following sub-topics: 1.Identifiers 2.Variables 3.Keywords 4.Statements 5.Comments 6.Whitespaces 7.Syntax 8.

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Coding Standards for C

Programming in C. What is C?... What is C?

from Appendix B: Some C Essentials

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

2. Numbers In, Numbers Out

Technical Questions. Q 1) What are the key features in C programming language?

This exam is to be taken by yourself with closed books, closed notes, no calculators.

2. Numbers In, Numbers Out

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

3.3 Structures. Department of CSE

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Online Judge and C. Roy Chan. January 12, Outline Information Online Judge Introduction to C. CSC2100B Data Structures Tutorial 1

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

Chapter 2: Overview of C. Problem Solving & Program Design in C

Compiling and Running a C Program in Unix

Functions BCA-105. Few Facts About Functions:

Final CSE 131B Spring 2004

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Approximately a Test II CPSC 206

C: How to Program. Week /Mar/05

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

Full file at C How to Program, 6/e Multiple Choice Test Bank

Review of the C Programming Language for Principles of Operating Systems

COMP s1 Lecture 1

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

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

Lab # 02. Basic Elements of C++ _ Part1

QUIZ. Source:

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Programming for Engineers Introduction to C

CS 361 Computer Systems Fall 2017 Homework Assignment 1 Linking - From Source Code to Executable Binary

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Approximately a Final Exam CPSC 206

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

CS : Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Documentation Requirements Computer Science 2334 Spring 2016

PRINCIPLES OF OPERATING SYSTEMS

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Introduction to C++ Introduction to C++ 1

Functions in C C Programming and Software Tools

Creating a C++ Program

APPENDIX A : Example Standard <--Prev page Next page -->

UNIT- 3 Introduction to C++

Model Viva Questions for Programming in C lab

QUIZ. What are 3 differences between C and C++ const variables?

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Use of scanf. scanf("%d", &number);

CSE 303 Lecture 8. Intro to C programming

CS 253: Intro to Systems Programming 1/21

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Chap 0: Overview. Overview of basic C++ syntax Refresh programming basics C++ Vs. Java differences Coding conventions used. EECS 268 Programming II 1

CSE 333 Lecture 7 - final C details

6.096 Introduction to C++ January (IAP) 2009

COSC121: Computer Systems: Runtime Stack

Variables. Data Types.

C Coding standard. Raphael kena Poss. July Introduction 2. 3 File system layout 2

C / C++ Coding Rules

Fundamental of Programming (C)

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

Transcription:

C Language Coding Standard For CS1003, CS1013, and CS2635 Rick Wightman Faculty of Computer Science University of New Brunswick Fredericton, NB January, 2001

INTRODUCTION Programming is a craft. Skill in a craft requires artistic talent, or creativity, and the application of discipline. The purpose of a program is to communicate a fully specified set of instructions to the computer; however, there is an equally important requirement for a program to communicate to other programmers: it's author, the development team members, the maintenance programmers over the entire lifespan of the program. Also, within education and open source communities, source code is treated as educational text with the expectation that it be treated with the same care as a traditional textbook. The skill of discipline is part of this process and is formally expressed through coding standards. Standardizing the mechanics of code construction allows the programmer to focus on the creative aspects knowing that others can easily appreciate and understand what is intended and how it is accomplished. To liken this process to writing an essay: if you don't have to think about how to form thoughts into sentences and then paragraphs; if you have a command of the language and you understand its grammar and syntax, then you can focus all of your efforts on expressing yourself effectively and the essay will flow with relatively little effort. If you are missing this skill, then readers spend their time trying figure out what exactly you are trying to say instead of following your train of thought and thinking about what it means. More immediately, the programmer spends much more time programming. So coding standards are important. What follows is a set of coding standards appropriate for use within undergraduate courses in the UNB Faculty of Computer Science curriculum that use the C programming language. They are not intended to be definitive. They are intended to provide guidance for small programming efforts typical in undergraduate courses. The coding standard is discussed in terms of overall program source file organization, function organization, statement organization and naming of functions and variables. Lastly there is a discussion of the role of library functions within courses. Following this, an example program attempts illustrates the implementation of the coding standard. SOURCE FILE ORGANIZATION There can be many sections to a program source file. The following discussion presents a description of each section. The ordering presented here should be used. Not all of the section types will necessarily be used in all programs, in which case don t put them in. Each of the sections should be clearly identified within the program source file using comments and white space (blank lines). File Documentation The first item in a source file should be a comment block identifying the name of the file, it s author and what functionality the code provides. Each individual function within the file should also have a comment block naming the function and the functionality it provides. Preprocessor Information This section should list the header files that are needed (#include), followed by the preprocessor macros (#define as well as others). Preprocessor macro names should use capital letters only. Type Definitions These are programmer defined data types, named using the C keyword typedef. Within some programming teams, struct definitions, without the associated variables but with the fields C Language Programming Standard (January, 2001), page 2

listed are also heavily used. This avoids introducing both a typedef identifier and a structure for infrequently used structures Function Prototypes Prototypes for all programmer defined functions should be presented. The arguments should be specified with both data type and name (e.g. float fxvalue ). The main Function This is the main program (function) body. It should be preceded by a comment block describing what it does. This function must be present in programs contained in a single source (.c) file. For larger programs divided into several source files, it must be present inexactly one source file. Functions Functions should be listed last. Ordering of the functions themselves is at the discretion of the programmer; however a top-down approach is suggested.. This means that the first functions defined should be those that are called from the main and that function calling no other function are listed last. Each function should be preceded by a comment block listing what duties the function performs. FUNCTION FORMAT As already stated, the function should be preceded by a comment block. All functions except the main will have a prototype listed in the prototype section of the program source file. The main function must be of type int (i.e. int main() )must return an appropriate completion code. The following discussion should be applied. The function should have at least three identifiable sections: variable declaration; function code and function return. Variable Declaration All variables to be used in the function will be listed immediately following the function s opening brace. Variables will be listed, one per line, with an inline comment describing its purpose. All variables within a program source file are to be declared within a function. Global variables are not to be used, except in specific circumstances accompanied by careful discipline and extensive style rules that are outside of the scope of this document. Function Code The function code performs that task required of the function. Function Return The return statement (return) should appear as the last statement in the function. The return statement may be optional for functions of type void for some programming projects. STATEMENT (BLOCK) FORMAT Statement (code) blocks should set off by indenting using a tab. The opening brace of a statement block should stand by itself in a line, as should the closing brace with neither brace being themselves indented. An inline comment may be useful after the closing brace to identify what it closes. Within a statement block it may be useful to separate tasks using blank lines. Statements that exceed the width of the screen (or the width of a printed page) should be broken into C Language Programming Standard (January, 2001), page 3

more than one line so that the continuation line is indented from the parent line. NAMING This is an incredibly important area that beginning (and other) programmers overlook. The naming of a function or variable should leave little question about the purpose it serves within the program. There are several different, widely used standards for naming, i.e. choosing identifiers. It will be necessary to follow whichever standard is prescribed for the project. Course work should follow the standard in this document unless the instructor specifies otherwise. Functions Function names should be meaningful. Names made up of multiple words should have the initial letter capitalized, except for the first word (e.g. calcfuturevalue). Variables Variable names should follow the same pattern as function names with one additional complication: the variable name should be prefaced by data type identifiers. The identifier scheme is as follows: Name Data type Prefix Example Character char c cinitial Short Integer short i idicevalue Integer int i inumberofmarks Long Integer long l lworldpopulation Single-precision Real float f fstudentmark Double-precision Real double d dxcoordinate String char or char [] s sstudentname Pointer <type> p plworldpopulation Style The use of side-effects is discouraged since it detracts from readability and comprehension. There should be no more than one statement on each line. White space (blank lines) should be added to space out statements for added readability. LIBRARY ROUTINES Use of Library Routines The student is expected to use library routines that have been covered in the course, or in a prerequisite course, when they will simplify the program. For example, rather than write code to copy a string, students would be expected to use strcpy().the exception to this rule would be when writing this code is part of the assignment (e.g. Write a function that demonstrates how the strcpy() function might be coded. ). Generally C programmers should make heavy use of the string (e.g. strcpy() ), character (e.g. isalpha() ) and standard i/o (e.g. printf() ) library C Language Programming Standard (January, 2001), page 4

functions. Prototypes for Library Routines Use of the correct prototype for each library routine is required. This prototype must be supplied by providing the correct header (.h) file by means of an #include statement. Under UNIX and Linux, the command man command can be used to determine the correct.h file. Most compilers include an option (e.g. -Wall for gcc) that reports on failure to provide a prototype. The gets() Library Function Use of the standard i/o function gets() is absolutely prohibited since it introduces an unavoidable security hole and/or bug into every program it is a part of (see, e.g. Stevens, W. Richard. 1993. Advanced programming in the UNIX environment. Addison Wesley. Pp 130-131). C Language Programming Standard (January, 2001), page 5

SAMPLE PROGRAM SOURCE FILE template: a template for the construction of C language program source files. Presents a solution for calculating the length of a line from its composite segments Author: Rick Wightman, 61340 CS1003 University of New Brunswick Fredericton, NB Created: 24 December, 2000 Modified: / REQUIRED HEADER FILES / #include <stdio.h> #include <math.h> MACRO DEFINITIONS / #define MAXCOORD 100 FUNCTION PROTOTYPES / float calchypotenuse(float x1, float y1, float x2, float y2); MAIN PROGRAM / main: Accepts x y values from the keyboard and calculates the hypotenuses (distances) between the coordinates / int main(int argc, char argv[]) float fxcoord[maxcoord]; x values from input / float fycoord[maxcoord]; y values from input / int incoord; number of values in above arrays / float fsegmentlength; calculated segment length / float flinelength; calculated sum of segments / int ielement; Loop counter / Get x and y values. / printf("line Length Calculator:\n\n"); do printf("number of x/y values to be entered: "); scanf("%d", &incoord); if(incoord < 2) printf("at least two points must be specified\n"); }while(incoord < 2); Calculate each segment length and print it out. C Language Programming Standard (January, 2001), page 6

Sum the total line length / flinelength = 0.0f; for(ielement = 0; ielement < incoord-1; ++ielement) fsegmentlength = calchypotenuse( fxcoord[ielement], fycoord[ielement], fxcoord[ielement+1], fycoord[ielement+1]); flinelength += fsegmentlength; printf("segment %d\t(%f,%f) to (%f,%f):\t%f\n", ielement+1, fxcoord[ielement], fycoord[ielement], fxcoord[ielement+1], fycoord[ielement+1], fsegmentlength); } End for(i... / Print out the line length / printf("-----------------------------------\n"); printf("length of line: %f\n",flinelength); return 0; } End main() / FUNCTIONS / calchypotenuse: calculate the distance between two 2D points inputs: two floating point coordinates: x1,y1 and x2,y2 returns: a floating point value of the distance between the input points. uses: <math.h> / float calchypotenuse(float fx1, float fy1, float fx2, float fy2) float fdeltax; float fdeltay; float fhypotenuse; calculate the differences for X and Y / fdeltax = fx2 - fx1; fdeltay = fy2 - fy1; calculate the distance / fhypotenuse = (float) sqrt( fdeltaxfdeltax + fdeltayfdeltay ); return fhypotenuse; } End calchypotenuse() / END / C Language Programming Standard (January, 2001), page 7