C Formatting Guidelines

Similar documents
Fundamental of Programming (C)

Coding Standards for C

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

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

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

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

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

Fundamentals of Programming

CSCI 262 C++ Style Guide

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Coding Standards for C

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

6.096 Introduction to C++ January (IAP) 2009

A Fast Review of C Essentials Part I

C Coding Standards. Alan Bridger UK Astronomy Technology Centre Mick Brooks, Jim Pisano National Radio Astronomy Observatory

Syntax and Variables

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

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

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

DEPARTMENT OF MATHS, MJ COLLEGE

EE 382 Style Guide. March 2, 2018

Flow Control. CSC215 Lecture

INTRODUCTION 1 AND REVIEW

CMPE-013/L. Introduction to C Programming

Key Differences Between Python and Java

Programming Style Guide v1.1

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

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


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

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

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

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

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

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

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

Computer Components. Software{ User Programs. Operating System. Hardware

Topic 6: A Quick Intro To C

BLM2031 Structured Programming. Zeyneb KURT

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

Advanced use of the C language

LECTURE 02 INTRODUCTION TO C++

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

CSE 142/143 Unofficial Style Guide

C Syntax Out: 15 September, 1995

UNIT- 3 Introduction to C++

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

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

EL6483: Brief Overview of C Programming Language

Computer Programming : C++

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Coding Convention for ECON 41701

YOLOP Language Reference Manual

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

COMP322 - Introduction to C++

Programming. C++ Basics

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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

CSCI 171 Chapter Outlines

Have examined process Creating program Have developed program Written in C Source code

Visual C# Instructor s Manual Table of Contents

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

CS 351 Design of Large Programs Coding Standards

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Programming and Data Structures

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

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

Programming in C UVic SEng 265

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

Short Notes of CS201

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

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

Creating a C++ Program

Types, Operators and Expressions

CS201 - Introduction to Programming Glossary By

Introduction to C Programming

Basics of Java Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

G52CPP C++ Programming Lecture 9

COMP 202 Java in one week

Course Coding Standards

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

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

CSE 11 Style Guidelines

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C CODING STANDARDS AND PRACTICES ENTC 489 EMBEDDED REAL TIME SOFTWARE DEVELOPMENT REVISION 1.0 CODESTD.DOC

Transcription:

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING CMPE13/L: INTRODUCTION TO C PROGRAMMING SPRING 2012 C Formatting Guidelines Lines & Spacing 1. 100 character lines (tabs count as 4 characters) and this includes comments. Example code adhering to this style guideline is shown in examples: [8, 9] at the end of this document. 2. Broken lines should be broken at sensible spots. After a comma in a function argument list At a reasonable point in a string (not in the middle of a word). [8] After operators in an expression. [9] 3. Broken lines should be indented further in, ideally being right-aligned with the line above. [8, 9] Indentation pass the tab-point of the parent line should only use spaces so the code remains readable even with different tab sizes. 4. All code blocks should increase their indentation by 1 tab character as they're nested. [4] 5. Code within #ifdef s and the like should be indented to match where they would be inserted into the code if possible to increase readability. [16] 6. Macros should be split into multiple lines if they include complex logic. [3] 7. All non-unary operators should have spaces separating them from their operands. [5, 6, 7] 8. Commas should always be followed by a space. [15] 9. Array initialization with curly-braces should not include spaces between the braces and the array element values. Parentheses should also not include spaces inside the parentheses. [4] 10. Switch statements should include their case conditions at the same indentation as the switch itself. Therefore the actual code should sit one indentation in from the switch statement. [14] 11. Struct member operators (., -> ) should not be surrounded by spaces. [4] 12. There should be no spaces at the ends of lines. 13. Hexadecimal numbers should be written in all upper-case. [5] 14. The asterisk used when referring to pointers ( * ) should be directly next to the variable name with no spacing. [4, 7, 8] 15. Lines should only contain a single statement, so generally one semi-colon per line. [4, 5, 7] Special case is for-loop declarations. [3, 10, 15] Headers 1. Header files should include header guards. [12] Header guards protect code from being included in files multiple times, which can cause errors.

Braces This follows an #ifndef X; #define X; HEADER_FILE_CODE; #endif; pattern, where X is an underscored and uppercased version of the header s filename 2. Headers should only include the necessary files for the header to compile properly. All headers that are only necessary for the corresponding C-file should be included directly in that file. 1. Curly-braces ({) should surround every control statement that can have them (if, else, while, etc) even if the body has only a single line of code. [13] This improves readability through consistency and prevents errors when modifying code. 2. Curly-braces around functions should exist on their own lines separate from the function header. [17, 18] Comments 1. Comments should be written as inline comments // unless declaring large sections of code or functions. [4, 11] 2. Comments can exist on the same line as code, but this should keep in line the 100 character limit for a single line. This is also reserved for initial variable declarations and useful for documenting struct members inline. [4] 3. Block comments ( /* */ ) should be used to comment general areas of code, such as the location of header files, macros, and function prototypes. The left hand side of each line within the block comment should start with a space and an asterisk ( * ) and the ending line should be a space, asterisk, forward slash ( */ ). [15] 4. Function and macro-function block comments should follow the same rules as regular block comments but include an extra asterisk on the first line so it should look like ( /** ). [1, 12] 5. Function and macro-function block comments should include the valid input for the function, expected output, error handling, and anything else relevant such as whether the return point has been malloc()ed and will need to be manually free()d. [18] 6. Comments should not describe what the code is doing unless it is at a very high level. Just describing the code is redundant as the code should already be readable. Comments should focus on why this code is this way or noting any other peculiarities of it. [13, 14] Naming 1. Functions should be named in a NounVerb capacity such as MatrixPrint() or MatrixScalarAdd(). [18] 2. Functions that are contained within the same module should be prefixed with the module name or something else that makes sense. [12] For example the MatrixMath.h library uses Matrix as the prefix for all of its functions. 1. Functions, structs, and enums should follow an upper-camelcase convention where all words and acronyms are squished together without underscores and the start of each one is capitalized. Acronyms should count as a single word and as such should only have their first letter capitalized. Good examples are MatrixPrint(), CanMessage (CAN is an acronym), and ListInsertAfter().

2. Variable names should follow a lower-camelcase convention which only differs from the above convention in that the first word is NOT capitalized. 3. Variable names should avoid long and overly similar names where possible (like the pair arrayindexupperbound and arrayindexlowerbound) as they are hard to distinguish. 4. Variable names should be named to be indicative of their use. They should only be used for that purpose unless memory use is a factor. 5. Macro names should be all uppercase and use underscores for word separation. [1, 2, 3] 6. If temporary variables are required, name them something that involves tmp, temp, or temporary, e.g. tmp or TempCalculation. Ideally place this code in its own code block so that the variable is out of scope later and so doesn't need to be unique. In this way you avoid conflicts and having to use numbering with the variables. 7. Single-letter variables should be lower-case. These are only valid for counter variables for loops. For integers use the standard convention of i, j, k, l, m, or n. Scope & Organization 1. All structures in C should exist in the smallest scope necessary to provide the desired API Don't expose structures, variables, functions that other code shouldn't use 2. Functions should be limited to the scope they're necessary in. Functions internal to a module should NOT be declared in the header and exposed to other programs. 3. Global variables that are only necessary in a single C-file should be declared static and thus limited to the file s scope. 4. Code should be logically grouped into small segments by using empty lines as a separator. [4] 5. C-files for libraries should be organized as follows: 1. File comments name, software license, broad description, etc. 2. Included files Including the corresponding header file for this file. Grouped into system files (those included with <>) and user files (those included with ) 3. Data type definitions 4. Internal macro declarations These macros would be only for use within this C-file. Macros that are part of the library should be placed in the header file. 5. Global and external variable declarations 6. Functions definitions 7. Test harness (blocked out by #ifdef; TEST CODE; #endif) 6. C-files for the file with main() should be organized as follows: 1. File comments name, software license, broad description, etc. 2. Included files Grouped into system files (those included with <>) and user files (those included with ) 3. Data type definitions

4. Internal macro declarations These macros would be only for use within this C-file. Macros that are part of the library should be placed in the header file. 5. Global and external variable declarations 6. Internal function prototypes These prototypes would be only for functions defined and used only within this C-file. 7. main() 8. Internal function definitions These functions are only for use within main() and other functions within this file. Functions for external use should be moved into an additional module. Macros 1. Macros should use parentheses around any input arguments. [1, 3] 2. Any magic numbers, numerical constants with special meanings, used within the code should be instead referred to via a macro. [2, 14] This will generally exclude loop termination conditions. Usually this refers to any constants used in the code. 3. Macros should never affect control flow! This negatively affects both readability and debugging. Avoid break, continue, and return within a macro. 4. Parentheses should also surround the entire macro if they re not just constants. [1] Code examples 1. Example 1 /** * Calculates the length of the third side of a triangle given the other two sides based on * the Pythagorean theorem. Note that x and y will be evaluated twice in the macro so be careful. */ #define PY(x, y) (sqrt((x) * (x) + (y) * (y)) 2. Example 2 // The constant pi that relates to circles and trigonometry. #define PI 3.14159 3. Example 3 #define LIST_LOOP(cons, listp) \ for ((cons) = (listp);!nilp (cons); (cons) = XCDR (cons)) { \ if (!CONSP (cons)) { \ signal_error ("Invalid list format", (listp)); \ \ \

4. Example 4 // A point specified in circular coordinates. struct Point { double Angle; // Units in radians double Radius; // Units in meters ; struct Point origin = {0.0, 0.0; if (zoomvalue > 8.0) { origin.angle = M_PI; origin.radius = 1; struct Point *originreference = &origin; originreference->radius = 0.0; originreference->angle = 0.0; 5. Example 5 int debugspeed = (++i << 5) ^ 0x7FFE; 6. Example 6 unsigned int bittoset = 1 << (3 ((message.buffer & 1) << 3)); 7. Example 7 uint32_t output[3]; output[1] = ((uint32_t)msg.payload[3]) << 24; output[1] = ((uint32_t)msg.payload[2]) << 16; output[1] = ((uint32_t)msg.payload[1]) << 8; output[1] = (uint32_t)msg.payload[0]; output[2] = ((uint32_t)msg.payload[7]) << 24 ((uint32_t)msg.payload[6]) << 16 ((uint32_t)msg.payload[5]) << 8; (uint32_t)msg.payload[4]; output[3] = (((uint32_t)msg.validbytes) << 16); 8. Example 8 char *HelloString = Are you still there? I see you. Hello? Critical error. Sorry. I don't hate you

. Why? No hard feelings. ; 9. Example 9 unsigned long BitToSet = (1 << (3 ((message.buffer & 1) << 3))) & (++i << 5) ^ 0x7FFE) ((unsigned long)msg.payload[3]) << 24; 10. Example 10 int i; for (i = 0; (i < lim - 1) && ((c = getchar())!= EOF) && (c!= '\n'); ++i) { s[i] = c; 11. Example 11 // Transmit the 6-byte message via UART1. int bytestotransmit = 6; int i = 0; while (i < bytestotransmit) { PutsUART1((unsigned int)txmsg[i++]); 12. Example 12 EcanFunctions.h: #ifndef ECAN_FUNCTIONS_H #define ECAN_FUNCTIONS_H /** * Pops the top message from the ECAN1 reception buffer. It returns a tcanmessage struct with the * older message data. */ struct CanMessage Ecan1Receive(); #endif // ECAN_FUNCTIONS_H EcanFunctions.c: #include EcanFunctions.h #include Buffer.h // Keep a circular buffer for the received CAN messages. static struct CircBuffer ecan1rxbuffer; struct CanMessage Ecan1Receive() { return BufferReadFront(&ecan1RxBuffer);

13. Example 13 // Set transmission errors in first array element. if (C1INTFbits.TXBO) { errors[0] = 3; else if (C1INTFbits.TXBP) { errors[0] = 2; else if (C1INTFbits.TXWAR) { errors[0] = 1; // Set reception errors in second array element. if (C1INTFbits.RXBP) { errors[1] = 2; else if (C1INTFbits.RXWAR) { errors[1] = 1; 14. Example 14 // A little Boolean emulation for C #define TRUE 1 #define FALSE 0 // Control the mux for the command inputs between autonomous or manual mode. switch (runningmode) { default: case AutonomousMode: driveswitch = FALSE; rudderswitch = FALSE; break; case ManualMode: driveswitch = TRUE; rudderswitch = TRUE; break; 15. Example 15 /* * Include standard libraries. */ #include <stdio.h> #include <math.h> int i, j; for (i = 0, j = 0; i < 10; ++i, j = pow(i, 2)) { printf( %d^2 = %d\n, i, j);

16. Example 16 #ifdef PIC24F #include "p24fxxxx.h" #else #error This code was designed for the PIC24F on the Explorer16 development board. #endif 17. Example 17 int main() { printf( Hello World!\n ); return 0; 18. Example 18 /** * Integer division function. Valid input ranges for a and b are any valid integers. If b is 0 * then the return value will be 0.0 as this is an invalid computation. */ double IntegerDivide(int a, int b) { if (b == 0.0) { return 0.0; else { return (a / b);