You are on page 1of 52

1

Internal Document

C Coding Standard
Release <Software Release Number>
<DocNum> Rev. X0
Document Version <1.2>
15 October, 2008
KWC-SWAT Team

2 Kyocera Proprietary
3 Export of this technology or software is regulated by the U.S. Government.
4 Diversion contrary to U.S. law prohibited.

6Data and information contained in or disclosed by this document are proprietary information of Kyocera
7Wireless Corp., and all rights therein are expressly reserved. By accepting this material, the recipient agrees that this material and
8the information contained therein are held in confidence and in trust and will not be used, copied, or reproduced in whole or in
9part, nor its contents revealed in any manner to others without the express written permission of Kyocera Wireless Corp.
10
11

12 Kyocera Wireless Corp.


13 10300 Campus Point Drive
14 San Diego, California 92121-1714
15
16 Copyright © 2001 Kyocera Wireless Corp. All rights reserved.
17 Printed in the United States of America.
18
19 <DocNum> Rev. X0
20 Document Version <1.2>
21 1 September, 2004
22
23 Kyocera Proprietary
24C Coding Standard Internal Document Contents
25Release <Software Release Number>

1 Contents

2 Table of Contents
3

41 Introduction................................................................................................................................1
52 Naming Standards.....................................................................................................................2
6 2.1 General Considerations in Naming........................................................................................2
7 2.2 File Names.............................................................................................................................2
8 2.3 Variable and Function Names................................................................................................3
9 2.3.1 Basics...............................................................................................................................3
10 2.3.2 Visibility (scope) of Names.............................................................................................4
11 2.3.3 #define..............................................................................................................................4
12 2.3.4 typedef..............................................................................................................................5
13 2.3.5 enum.................................................................................................................................5
14 2.3.6 struct.................................................................................................................................5
15 2.4 Pseudo-Hungarian Notation...................................................................................................6
3 File Organization.......................................................................................................................7
16

17 3.1 Header (.h) files.....................................................................................................................8


18 3.1.1 Header File Identifier (double-inclusion preventer)........................................................8
19 3.1.2 Header File Comment......................................................................................................8
20 3.1.3 Nesting of Header Files...................................................................................................9
21 3.1.4 Variable Declarations in Header Files..............................................................................9
22 3.1.5 Function Declarations in Header Files.............................................................................9
23 3.2 Source (.c) files......................................................................................................................9
24 3.2.1 Source File Comment......................................................................................................9
25 3.2.2 Declarations of file-local (static) functions....................................................................10
26 3.2.3 Function Headers...........................................................................................................10
27 3.2.4 Logic Headers................................................................................................................10
28 3.3 Templates.............................................................................................................................10
29 3.4 Copyright.............................................................................................................................10
4 Code Formatting......................................................................................................................12
30

31 4.1 Code formatters....................................................................................................................12


32 4.2 Whitespace...........................................................................................................................12
33 4.3 Long Lines...........................................................................................................................13
34 4.4 Operator Precedence............................................................................................................13
35 4.5 Conditional and Mathematical Operations..........................................................................14

26KWC-SWAT Team <DocNum> Rev. X0 8865897.doc


271 September, 2004 Kyocera Proprietary Page iii
28C Coding Standard Internal Document Contents
29Release <Software Release Number>

1 4.6 Loop Control Conditions.....................................................................................................14


2 4.7 Indentation and Braces.........................................................................................................14
3 4.8 Tab Characters.....................................................................................................................16
4 4.9 Function Declarations..........................................................................................................16
5 4.10 #ifdefs................................................................................................................................16
65 Comments.................................................................................................................................18
76 Miscellaneous............................................................................................................................19
87 Revision History.......................................................................................................................21
9Appendix A File Templates.........................................................................................................22
10 A.1 Header File (.h)...................................................................................................................22
11 A.2 Source File (.c)....................................................................................................................23
Appendix B Religious War – Tabs vs Spaces............................................................................27
12

Appendix C Auto Syntax Expansion.........................................................................................30


13

14 C.1 Auto Syntax Expansion Triggers.........................................................................................30


15 C.2 Visual Studio Setup.............................................................................................................33
16 C.3 Visual SlickEdit Setup.........................................................................................................34
Appendix D Robust Function Format......................................................................................35
17

18 D.1 Description..........................................................................................................................35
19 D.1.1 Speed -> Robustness Tradeoff......................................................................................35
20 D.1.2 ‘Helper’ Function Exception.........................................................................................35
21 D.2 Function Format..................................................................................................................35
22 D.2.1 Before we Begin: Embrace Paste & Replace................................................................35
23 D.2.2 Function Comments......................................................................................................36
24 D.2.3 Function Declaration.....................................................................................................37
25 D.2.4 Function Body...............................................................................................................38
26 D.2.5 Functional Logic...........................................................................................................39
27 D.2.6 Error Handling..............................................................................................................40
28 D.2.7 Output Validation (Success Case).................................................................................40
29 D.2.8 Cleanup.........................................................................................................................41
30 D.3 ‘THE’ example...................................................................................................................41
Appendix E Generic Status Codes.............................................................................................43
31

32 E.1 Bitwise Breakdown.............................................................................................................43


33 E.2 Group Codes........................................................................................................................43
34 E.3 Sub-Group Codes................................................................................................................43
35 E.4 Sub Codes............................................................................................................................44
36 E.4.1 Text Widget Example:...................................................................................................44
37 E.4.2 Declaring Status Codes..................................................................................................45
38 E.5 Status Macros......................................................................................................................45

30KWC-SWAT Team <DocNum> Rev. X0 8865897.doc


311 September, 2004 Kyocera Proprietary Page iv
32C Coding Standard Internal Document Contents
33Release <Software Release Number>

1 E.6 Why Use Generic Errors?....................................................................................................45


2 E.7 Why return status codes rather than pass by reference?......................................................46

34KWC-SWAT Team <DocNum> Rev. X0 8865897.doc


351 September, 2004 Kyocera Proprietary Page v
36

1 1 Introduction

2Consistency is desirable in many undertakings and software production is one of them. While
3there exist good reasons that programmers each like what they like in terms of code aesthetics,
4productivity increases across a large team of programmers when they all know what to expect,

5and how to understand it, when they read one another’s work. The fact that any one of them

6won’t like some aspects of the code they see — and even, the code they write — is far less im-

7portant to a business than the time and effort wasted in supporting the “individuality” of varying

8coding styles.

9 So we present a single Coding Standard for you to follow in doing your work. As a part of the
10large group of skilled engineers doing their programming here, you leave some of your prefer-

11ences behind and tolerate a few mildly-distasteful things you’ll find mandated in this standard.

12At the same time, you gain far more from not having to tolerate everything that all those other

13engineers would inflict on you if a single standard didn’t exist.

14And that’s focusing entirely on stylistic preferences, perhaps the least critical aspect of what is
15gained from applying a Coding Standard. Much of this standard is focused on conventions that
16provide semantic context for you when reading code. And as you’ll see, we mandate a few things

17here that actually serve to avoid bugs.

18And yet there may be situations in which the standards laid out in this document are inappropri-
19ate or painfully inconvenient — engineers should consult with their team leads about how best to
20proceed. Although making exceptions is possible, questions will likely arise at code reviews. In

21general, it is best to involve those responsible for maintaining this set of coding standards when

22an exception seems necessary; it may be that the standards themselves should be changed.

37KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


381 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 1
39

1 2 Naming Standards

2The purpose of naming standards is twofold: to increase source code consistency across multiple
3projects and to provide semantic information to readers of the source. Such information includes
4intended usage, location of declarations, special behaviors, and sometimes type indicators.

52.1 General Considerations in Naming


6First, the extremely obvious guideline underlying all that follows: Names must be descriptive
7and self-documenting. This does not, however, preclude brevity. Nor does it explicitly disallow

8single-character names in identifiers.


1

9 Names are to be as long as necessary in order to convey relevant meaning about their contents or
10function. That said, it’s important to take a moment when creating a new name and focus on how

11best to convey its meaning succinctly. Using commonly known abbreviations, omitting of extra

12(though not all) vowels, using digits in place of words, etc — these are all desirable tricks to re-

13tain meaning while shortening names.

14In general, names of 8 to 18 characters in length (not counting required prefixes and suffixes)
15turn out to be sufficient, although there will be exceptions. There is no set minimum or maxim-
16um length.

Projects tend to use brief (three- or four-character) acronyms to identify themselves. This prac-
17

tice is useful and should be applied within externally visible names.


18

2.2 File Names


19

Filename length is a matter of surprising relevance, since portions of filenames are used within
20

identifiers in the source code (as explained in section 2.3).


21

22Having declared a strong preference for succinct (as compared to needlessly long) names, we
23note that there exists no reason to constrain filenames to eight characters. This is not 1983. There
24may be cases where compatibility with third-party products or processes does require use of

25DOS-style filenames. Only team leads may make this determination and they are to make it

26loudly and publicly so everyone can understand that their project has special needs and is not the

27desired rule. Even in such cases, it is worth the team lead’s time in checking to see if such a re-

28striction really does exist, rather than just assuming it might.

Filenames follow the same character rules as C language identifiers, with two further qualifica-
29

tions:
30

1 The major application of single-character names is as loop control variables in small loops, which is quite reasonable. Beyond
40
41that usage, however, one must be prepared to pay for the privilege of less typing when one’s code is reviewed.

42KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


431 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 2
44

1 • Filenames are entirely lower-case, and


2 • They do not contain underscores.
3These requirements can result in run-on names where more than one word exists in a name (ex-
4ample: uiwaytoolongshortenthisnamecleanupfuncs.c). Yet there is a reason: por-
5tions of filenames are used within identifiers in the source code. Identifiers are subject to conven-

6tions about underscores and capitalization (those conventions are explained in section 2.3).

7Keeping filenames lower-case without underscores avoids conflicts across the set of conventions

8we apply for identifiers in the source code.

9 Also, Windows does its own mangling of upper and lower case in filenames for the purpose of
10display. We require that filenames not be subject to cross-platform difficulties. When creating a

11new source file, ensure that its name is entirely lower-case, despite whatever mangling the OS

12may be configured to do on your workstation for displaying names.

2.3 Variable and Function Names


13

2.3.1 Basics
14

15All names begin with a letter, not an underscore. Names end with a letter or digit, not an under-
16score. We have two different naming conventions for separating words within a variable name:

17underscores or Pascal and Camel casing. Underscores can be used with code close to the qct lay-

18er (Qualcomm’s code) to maintain consistency with that.

19Pascal/Camel case can be used in new code to reflect the newer style of code at large in the com-
20puter community. Pascal case convention capitalizes the first letter of each word and is what is
21used for function names. Camel case is like Pascal case, except the first letter of the name is

22lowercase; this is used for variable names.

Underscores – Qct code


23

24 name_with_four_parts

Pascal Case – Function Names


25

26 FunctionWithFourParts

Camel Case – Variable Names


27

28 nameWithFourParts

We also encourage you to use the VerbNoun naming convention for functions. I.e. describe what
29

action you’re going to take, then what you’re acting upon.


30
31 kal_OpenSocket()
32 kal_CreateSem()
33 ui_RotateBmp()
34 cp_MakeCall()

35

45KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


461 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 3
47

12.3.2 Visibility (scope) of Names


2Externally visible names of any kind (variables, constants, function names, type definitions, mac-
3ros, etc.) must be declared in a header file of the same name as the .c file where the name is
4defined. Each name includes a prefix consisting of the project id in lower-case followed by an

5underscore:
6 extern word16 projid_GlobalVar; // line in header file

7 Project ID is whatever the relevant team lead decides it is. Usually, it’s an indication of both the
8 code’s purpose and the organizational responsibility for it. There is much to be said for using
9project ID as the filename, at least as the leading part of the filename. The declaration line above

10would appear within the header file projid.h and a matching definition line would appear in

11projid.c.

12That being said, we are moving away from the use of underscores (qct code should be the only
13exception). So, do not get carried away with the prefixing of function names with many

14prefix/underscore combinations:

15 [projid]_[package]_[object]_[DoSomething] <–––– This is bad


Limit your function names to just one prefix (the project ID), then go ahead and use the Pascal
16

Casing Verb/Noun as described above.


17

18It can be daunting to apply the prefix-the-project-id convention where project id’s are long, but
19consistency along with reasonable brevity of project id’s provides more benefit than pain. Those

20of you with C++ experience may find it comforting to equate this convention with the use of

21class name qualifiers.

Variables and function names not externally visible outside a source file (declared within func-
22

tions or declared as static at file level) do not have to be prefixed with the file name.
23

24 static word32 LocalVar;


25
26 static void
27 FileScopeFunction ()
28 {
29 word32 SomeVariable;
30 }

31

32

33

2.3.3 #define
34

Any item declared in a #define (constant, macro, etc) is to be entirely capitalized and under-
35

scores are used to separate words contained within:


36
37 #define CONST_NUMBER_1 5000
38
39 Macros

Wrap each macro argument in an extra set of parenthesis to avoid any undesired side effects:
40
41 #define MACRO_WITH_ARGS( Arg1, Arg2 ) projid_SomeFunc( (Arg1) + (Arg2), TRUE )

If your macro contains multiple statements wrap it in a do {} while (0) statement:


42

48KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


491 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 4
50

1 #define CALL_TWO_FUNCS( ARG1, ARG2 ) do \


2 { \
3 Func1( (Arg1) ); \
4 Func2( (Arg1), (Arg2) ); \
5 } \
6 while (0)

7By wrapping the macro in a block it let’s you use that macro as a normal single statement, such
8as after an if statement, without having your second call not associated with the if. It also lets you

9stick a semi-colon after it without syntax error.

See http://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html for more discussion.


10

2.3.4 typedef
11

12The names of typedef items have a form similar to that of most identifiers; the rules for capit-
13alization and prefixing with filename (if externally visible) apply.
14 typedef short projid_Word; // externally visible
15
16 static typedef int BigWord; // file-local

17There do exist some exceptions to the typedef convention — a few system-wide cases which
18are so broadly applied that they’re considered “generic” and for which brevity is the main value.
19Examples are word16, word32, boolean, etc.
2

20

2.3.5 enum
21

enum types are declared using typedef


22

23 typedef enum // externally visible


24 {
25 ENUM_VAL_E = 42,
26 OTHER_VAL_E = 69
27 } projid_Blargle;

A.1.1
28

2.3.6 struct
29

struct types are declared using typedef.


30

31 typedef struct // externally visible


32 {
33 word16 Field1,
34 char *Field2
35 } projid_Smargle;

36

Fields within structs follow the same name rules as other variables, except that there is no project
37

id prefixed onto them.


38

2 Of course, these “generic” typedefs obviate the need for the very simple examples given here; generally, typedefs are applied
51
52for structs and enums.

53KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


541 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 5
55

2A.1
3

42.4 Pseudo-Hungarian Notation


5Pseudo-Hungarian notation is a set of conventions about adding prefix characters to identifiers in
6C code which tend to provide information about the type of the object being named. It gained
7widespread application through Microsoft’s use of it in the Windows API. The “Hungarian” as-

8pect comes from the fact that identifiers end up looking like words in a transliterated Hungarian

9text once the prefix characters have been added.

10In general, there is little need for pseudo-Hungarian notation any longer. Given context-sensitive
11editors, powerful source code browsers, compilers and code-checking tools capable of semantic

12analysis, there just isn’t much that Hungarizing of code adds to one’s day in programming. Other

13than preparing one for a vacation in Eastern Europe.

However, for teams that want to use it anyway, there are a few conventions to follow:
14

15 • The pseudo-Hungarian prefix is always lower-case and appears right next to the name
16 it precedes (that is, no underscores separating it from the rest of the name).
17 • The prefix appears at the very beginning of names for file-local variables and func-
18 tions.
19 • The prefix appears immediately after the underscore that follows the project id por-
20 tion for externally-visible variables and functions.
For example:
21
22 static word16 * pw16FileScopeVar; // file-local
23
24 word16 * projid_pw16GlobalVar; // externally visible

25The pseudo-Hungarian prefixes themselves may be defined by the team(s) upon which they are
26inflicted. Such teams are responsible for adequately documenting the meanings of all such pre-
27fixes and making that documentation available to anyone who wanders into the code.

56KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


571 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 6
58

1 3 File Organization

2A module (paired source files: filename.h and filename.c) is composed of related func-
3tions. Many small modules are not a problem; be generous in creating new ones. As a general

4rule of thumb, modules over about 1000 lines become awkward to maintain — consider splitting

5them up.

6Header (.h) files include the following components in this order:


7 1) Header file identifier (and double-inclusion preventer).
8 2) Header file comment with copyright, version, and documentation information.
9 3) System includes (<> syntax) for those system header files which are needed for the
10 declarations appearing in this header file, not those relevant only to the code which
11 appears in the matching source file.
12 4) Non-system includes (“” syntax) for those non-system header files which are needed
13 for the declarations appearing in this header file, not those relevant only to the code
14 which appears in the matching source file.
15 5) #defines for those constant values and macros conceptually “owned” by this mod-
16 ule, but also used in any other module.
17 6) Type declarations (struct, enum, typedef, etc) for those types conceptually
18 “owned” by this module, but also used in any other module.
19 7) Declarations of constants (variables declared as const) defined within this module,
20 but also used in any other module.
21 8) Declarations of variables defined within this module, but also used in any other mod-
22 ule.
23 9) Declarations of functions defined within this module, but also used in any other mod-
24 ule.
Source (.c) files include the following components in this order:
25

26 1)   
27 2) Source file comment with copyright, version, and documentation information.
28 3) System includes (<> syntax) for those system header files which are needed only for
29 the code inside this source file, not those needed for the declarations appearing in this
30 file’s matching header file.

59KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


601 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 7
61

1 4) Non-system includes (“” syntax) for those non-system header files which are needed
2 only for the code inside this source file, not those needed for the declarations appear-
3 ing in this file’s matching header file. Note that this section always includes at least
4 the header file associated with this source file.
5 5) #defines for those constant values and macros used only within this source file.
6 6) Type declarations (struct, enum, typedef, etc) for those types used only within
7 this source file.
8 7) Declarations of file-local (static) functions.
9 8) Definitions of externally visible constants (variables declared as const), declared
10 within the matching header file.
11 9) Definitions of externally visible variables, declared within the matching header file.
12 10) Definitions of file-local constants (variables declared as const and static) used
13 only within this source file.
14 11) Definitions of file-local (static) variables.
15 12) Definitions of externally visible functions, declared within the matching header file.
16 13) Definitions of file-local (static) functions, declared within this source file (at #3.

3.1 Header (.h) files


17

3.1.1 Header File Identifier (double-inclusion preventer)


18

Header files begin with the following directives:


19
20 #ifndef FILENAME_H
21 #define FILENAME_H

and end with:


22
23 #endif // FILENAME_H

where FILENAME reflects the file’s name (in this example, it would be filename.h). Note
24

that every line in the file besides the directives themselves appears inside the ifndef-endif pair.
25

These directives serve to prevent multiple inclusion of the header file and provide a handy identi-
26

fier tag for source code processing tools.


27

3.1.2 Header File Comment


28

29Header files have a standard block-style comment immediately after the file identifier. This com-
30ment includes bookkeeping items such as copyright, version, etc. Documentation information
31about the file’s purpose and contents may also appear here. There is a template upon which all

32header files are based, and this provides examples of what belongs in here. (See 7)

62KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


631 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 8
64

13.1.3 Nesting of Header Files


2Some projects prefer to avoid using #include within their header files. For the rest of the
3known universe, nesting of header files is common and very nearly inescapable. This coding
4standard does not preclude nesting header files, although it is left to team leads to set policy on

5this issue. The header file identifier (discussed in section 3.1.1) is expressly intended to make
3

6using #includes easier by avoiding all possibility of multiple inclusion and completely elimin-

7ating inclusion order as a concern.

8 The only #includes which should appear within a header file are those which resolve refer-
9ences that appear inside this header file — not in the matching source file. Any references which

10need resolving in the code there will be dealt with by #includes there.

3.1.4 Variable Declarations in Header Files


11

12Variables are declared as extern in a header file when they physically reside in the matching
13source file, but are referenced by other header or source files. At no time is a variable defined in

14a header file.

3.1.5 Function Declarations in Header Files


15

16Functions are declared as extern in a header file when their code is located in the matching
17source file, and they are called from within other source files. At no time is a function defined in
18a header file.

If a function is not called from within other source files, its declaration does not use the extern
19

keyword and is not to appear in a header file, but rather within the matching source file.
20

3.2 Source (.c) files


21

22

23

3.2.1 Source File Comment


24

25Like header files, source files have a standard block-style comment immediately after the file
26identifier. This comment includes bookkeeping items such as copyright, version, etc. Document-
27ation information about the file’s purpose and contents may also appear here. There is a template

28upon which all source files are based, and this provides examples of what belongs in here. (See

297)

3 We would encourage use of nested header files, to avoid placing upon people the burden of detecting all needed #includes,
65
66as well as dealing with ordering issues. We’ve considered the awful burden inflicted on the compiler during builds… but that’s
67what machines are for. Yet team leads are the ultimate decision-makers.

68KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


691 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 9
70

13.2.2 Declarations of file-local (static) functions


2All functions, even file-local ones, are to be declared prior to their definitions. Although declara-
3tions may not be technically required, they serve to remove ordering issues and provide a com-
4mon location for a list of all local functions within a source file.

53.2.3 Function Headers


6Each function should have a function header describing what the function does in broad terms,
7input parameters, return values, dependencies and any side effects it may have. See7 for a tem-

8plate header.

9 It is essential that you give a good description of what the function does before each function.
10You will not be the only one working on this function, so make the description clear enough for

11someone else to get a good idea of what the function should be doing before they have to start

12figuring out the code. And, no, the source code is not the description.

13Please keep this header information up to date as the function changes. Nothing is more annoy-
14ing than reading some function description about how the code below simply matches the incom-
15ing caller ID with a name from the Contacts listing, than to find out that now it looks it up, up-

16dates it automatically and sends an SMS to your sister.

3.2.4 Logic Headers


17

18Within a function, if you are doing anything that requires you to pause for a moment and think,
19put a descriptive comment about the code logic you are using. It is far quicker to read a couple

20sentences about what the code should be doing than it is to figure out the code from scratch.

21Having a general idea in mind, then looking at the code will help the next person see what’s go-

22ing on much better than having to draw out the code flow on scratch paper. And be sure to update

23the logic comments if you change the logic.

24

3.3 Templates
25

26Attached in the appendixes are template header and source files with bare bone skeletons of the
27file header comments and function header comments. Cut and paste from these when creating a
28new file or a new function.

3.4 Copyright
29

30This is the one portion of the Coding Standard that we have to bring in the sharks… err, Law-
31yers, I mean. We have code that we get from Qualcomm on a regular basis with their chips; this

32is the dmss stuff. We have code that we got from Qualcomm when Kyocera Wireless Corp. was

33formed. And, we have source code that, believe it or not, we wrote all by ourselves.

71KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


721 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 10
73

1Fortunately, what we have to do is pretty simple. Any code that we modify, add a copyright date
2for Kyocera to it. Be sure not to remove any copyright info already in the file. You can move the

3line around to fit into our template place for copyright info, just don’t get rid of any.

4List out each year, separated by a comma. When that line gets too long (>80 columns), add an-
5other line below it.
6 Copyright (c) 2002, 2003 by Kyocera Wireless Corp. All Rights Reserved.

7Any source file that you find without any copyright info, just add our standard header and, if you
8know, the years that that file existed. So, if it was written in 2001 add:
9 Copyright (c) 2001, 2002, 2003 by Kyocera Wireless Corp. All Rights Reserved.

74KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


751 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 11
76

1 4 Code Formatting

24.1 Code formatters


3 • GNU indent’s homepage at http://home.hccnet.nl/d.ingamells/beautify.html
4 • GNU’s page for indent at http://www.gnu.org/software/indent/
5 • indent++ at http://www.uvm.edu/~ashawley/c/indent/
6 • AStyle at http://astyle.sourceforge.net/

74.2 Whitespace
8Use it. A lot.
9For details on whitespace required by this coding standard, we provide the following examples,
as well as any other examples throughout this document:
10
4

11 • Put a space around assignment, logical, and comparison operators:


12 a = b;
13 c |= d;
14 if ( (a == b) || (c <= d) )

15 • Put a space after an open parenthesis, after a closing parenthesis, and after commas.
16 Put a space after a keyword (if, do, for, etc…) and before it’s parenthesis. Do not put
17 a space after a function name and its opening parenthesis:
18 until ( (a == b) && (c <= d) );
19 FunctionCall( FirstArg, SecondArg, ThirdArg );

20 • Do not put a space between the * pointer-dereference operator and the name to which
21 it applies:
22 a = *b;

23 Similarly, do not put a space after the * pointer-declaration character:


24 char *b;

25 And let multiple levels of pointer declaration chars run together:


26 char **c;

27 •
28 • Put at least one blank line between variable and function declarations in header files:
29 extern word32 projid_Fargle;

4 No, we don’t show function-header or other types of comments in these examples. The point here is whitespace, not comment-
77
78ing. We hit you with that elsewhere.

79KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


801 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 12
81

1
2 extern boolean projid_Fargled;
3
4 extern void projid_FargleIt();

5 • Put at least one blank line between segments within a switch statement, except
6 where the segments are so short (one or two lines) that the entire switch fits cleanly
7 into a small area:
8 switch ( BigSwitchController )
9 {
10 case First:
11 DoSomething( Complex );
12 . . . // <--- several lines not shown
13 break;
14
15 case That:
16 DoSomething( EvenComplexer );
17 . . . // <--- again, lines not shown
18 break;
19
20 default:
21 DoNothing();
22 }

23 • Put at least three blank lines between function definitions in source files:
24 void
25 projid_SomeFunc() // in source file
26 {
27 } // projid_SomeFunc
28
29
30
31 void
32 projid_SomeOtherFunc()
33 {
34 } // projid_SomeOtherFunc

35Please contact those responsible for the standard in any case where a question about use of
36whitespace remains (so that the question may be answered with your input, and the standard up-

37dated).

4.3 Long Lines


38

39Lines are to be broken at length 80. While this may seem short, given today’s large monitors, it’s
40a sad truth that someone will print the code — and they’ll add line numbers — through a printing
41program that doesn’t wrap lines, onto a page that’s 80 characters wide. Even when you’re sure

42that something, an editor or a print filter or whatever, will always wrap lines… do you want it de-

43ciding where to break the line, or you? Put aside laziness, go with the inner artist, and make

44these crucial decisions yourself.

4.4 Operator Precedence


45

Is evil. Don’t trust it. Don’t assume anyone else has learned it or really understood it.
46

47Logical conditions and mathematical calculations are to be fully parenthesized. Fully. Yes, even
48where it’s “obvious” what the intent of the expression is and the precedence rules “clearly” ap-
49ply. Such situations fall victim to typographical (&&, & ||, |, +, ++, etc) and pointer-dereferen-

82KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


831 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 13
84

1cing errors (*pName->Field, &pName->Field) which can be detected, or at least made


2more obvious in debugging, by always using more parentheses.

34.5 Conditional and Mathematical Operations


4A long string of logical conditions or mathematical operators is to be split onto separate lines. If
5possible, splits should follow the grouping of operators:
6 if ( ( Foo->Next == NULL ) &&
7 ( ( ( TotalCount < Needed) && ( Needed <= MAX_ALLOT ) ) ||
8 projidServerActive( CurrentInput ) ) )
9 {
10 ObscureHigherMathResult = ( TotalCount * MAX_ALLOT ) %
11 ( ( ( Needed * ( NewAndImproved + ShinyWhite ) ) +
12 ( MAX_ALLOT – 1 ) );
13 }
Where possible, the indentation of the extra lines should match the nesting level at which the
14

line’s contents belong.


15

4.6 Loop Control Conditions


16

Similar to complex conditions and mathematical operators, long loop control expressions are to
17

be split onto multiple lines:


18
19 for ( CurrentNode = *pList, LastNode = CurrentNode;
20 CurrentNode != NULL;
21 LastNode = CurrentNode,
22 CurrentNode = &(CurrentNode->Next) )
23 {
24 ...

The indentation of the extra lines should match the starting point of the previous line’s condition.
25

26Although this isn’t the section on naming, it is worth noting that loop control variables are one of
27the very few items for which single-character names may be appropriate. If nothing else, this can
28shorten a loop control expression to where it fits cleanly onto an 80-character line.

4.7 Indentation and Braces


29

30

31Two (2) spaces per level of indentation is used for new code. Always use spaces for indentation,
5

32not tabs. (See 7)


6

Indentation is always increased within braces (except as noted below for switch statements).
33

5 While not as close to the nerve as placement of braces, indentation style can seem pretty personal to programmers, too. Refer to
85
86the footnote on braces.
6 There are editor settings you should make to fit this convention. Note that some editors support the concept of indentation as
87
88distinct from tabs (for example, vi does it with the shiftwidth setting), and that capability is worth learning about and using. At
89the very least, you must configure your editor to replace tabs with spaces, if tabs are what you use to perform indenting.

90KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


911 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 14
92

1If-then-elses always have braces, as do all forms of loop. This consistency is more valuable than
2the rare savings of a few lines for skipping the braces around single-statement blocks.

3Braces are to be placed as follows: 7

4 • Braces for function definition appear in column 0:


5 int projid_Func()
6 {
7 . . .
8 }

9 • Braces for type declarations with subparts (structs, unions, enums) appear in column
10 0:
11 typedef enum // externally visible
12 {
13 ENUM_VAL_E = 42,
14 OTHER_VAL_E = 69
15 } projid_Blargle;

16 • Braces for nested code blocks (if-then-else bodies, loop bodies) appear on their own
17 lines at the indentation level of code where the block appears:
18 if ( FumingOverBracePlacement )
19 {
20 while ( Fuming )
21 {
22 CountToTen();
23 }
24 GetALife( AsSoonAsPossible );
25 }
26 else
27 {
28 HaveANiceDay( Today );
29 }

30 • The braces required for a switch statement appear on their own lines at the indenta-
31 tion level of the switch statement itself (similar to if-then-else braces). Braces are not
32 used for the segments within a switch statement:
33 switch ( ManyOptions )
34 {
35 case This:
36 DoSomething( Now );
37 break;
38 case That:
39 DoSomethingElse( Later );
40 break;
41 default:
42 DoNothing( Forever );
43 }

44 Note that the case values also appear at the indentation level of the braces. This is un-
45 usual, in that most code within braces is shifted at least one level to the right. This
46 convention keeps the actual code to be executed at its correct indentation level, while
47 visually separating out the values used in choosing which code to execute.

7 Placement of braces is a religious issue among programmers. We don’t intend to convert you. Prefer whatever you wish to
93
94prefer.
But we do require that you do it this way, preferences aside. The product of your efforts is not a demonstration of your
95preferences — it’s code that exists alongside that produced by lots of other people. Someone in that picture will not like
96something. Yet one thing must be done. Sorry, but cope with it.

97KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


981 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 15
99

14.8 Tab Characters


2Are evil. Use spaces. Always. (See 7) 8

34.9 Function Declarations


4Declare the function return type and function name on the same line. Use separate lines for open-
5ing and closing parenthesis and function parameters, so comments can be easily read. Give a de-
6cent description for each parameter your function takes.
7 SomeStruct MyNiftyFunction
8 (
9 int16 ResourceID, // Resource ID generated
10 // resource editor for the
11 // header file.
12 InfoStruct BunchOfInfo // Struct with more info for
13 // this resource
14 )
15 {
16 . . .
17 }

184.10#ifdefs
19We encourage the indentation of #ifdefs on the same level as the surrounding code. Obviously,
20for any #ifdefs that are outside of a function (like most at the begginning of the source file), this

21will mean to just stick them in column one. But even within an #ifdef block, indent subsequent

22#ifdefs appropriately. Note, that the #ifdefs are indent separately from the actual code.

23
24 //===================================================================
25 void build_ch_menu( uigm_page_field_type* pf )
26 {
27 …
28 /* Now create the scroll bar */
29 bbox = pf->rect;
30 #ifdef UIMM_SCROLLBAR_ON_LEFT
31 bbox.x = 0;
32 bbox.dx = 3;
33 #else
34 bbox.x = bbox.x + bbox.dx - 3;
35 bbox.dx = 3;
36 #endif
37 …
38 }
39
40 //===================================================================
41 #ifdef TMC_1X
42 #include "srch.h" // Srch header file
43 #include "rxtx.h" // RXTX header file
44 #if ( TG != T_PC ) // Define for all targets except Unit Test
45 #include "therm.h" // Thermister header file
46 #define TMC_HAS_HW_CONFIG
47 #endif // TG!=T_PC
48 #endif // TMC_1X
49
50 //===================================================================
51 LOCAL void tmc_libraries_init_before_tasks_start( void )
52 {

8 Configure your editor to replace tabs with spaces.


100

101KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1021 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 16
103

1 …
2 #ifdef TMC_1X
3 db_init(); // Database services
4 enc_init();
5 #ifdef T_MSM5000 /* Decoder driver */
6 deint_init();
7 #else
8 #error code not present
9 #endif
10 #ifdef T_MSM5000
11 #ifdef T_MSM4500
12 #error code not present
13 #else // T_MSM4500
14 #ifndef FEATURE_DMOD_IMAGE_IN_ROM
15 #ifdef T_MSM6050
16 // For T_MSM6300 target, demod... is done by rf_init_delayed()
17 #ifndef FEATURE_MDSP_TASK
18 demod_download_image( TRUE );
19 #endif
20 #else
21 #error code not present
22 #endif // T_MSM6050
23 #endif // FEATURE_DMOD_IMAGE)_IN_ROM
24 #endif // T_MSM4500
25 #endif // T_MSM5000
26 …
27 }
28
29

30

31

32

33

34

104KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1051 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 17
106

1 5 Comments

2Comments can use either the C (/* … */) or C++ (// … ) style of comments. The C++ style are
3appropriately used for single line comments, or trailing comments. Any comment beyond a few
4lines should use the C style for the comment block.

5 Those comments use the “C style” delimiters /* and */


6As described in sections 3.1.2 and 3.2.1, all header and source files start with a block comment
7describing in high-level terms the contents. There is usually a template upon which all header
8and source files are based, providing examples of such block comments.

9Every function definition is to be preceded by a block comment describing the purpose of the
10function, the arguments, the return value, and any side effects or dependencies.

All externally visible variables are to have a comment explaining the variable’s meaning and in-
11

12tended usage. Such a comment appears twice: at the declaration in the header file and also at the
13definition in the source file.

14Every #endif more than a few (on the order of 4) lines below its matching #if or #ifdef is
15to have a comment that shows the #if condition. Such comments are encouraged even when

16there are just a few lines, and they are required whenever nesting of #if/#ifdef directives ob-

17scures the affected areas.

18Comment lines within code are to be indented at the same level as surrounding code.

107KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1081 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 18
109

1 6 Miscellaneous

2Use include path directives rather than path information in #include statements.
3Switch statements are always to include a default case. Any fall-through (segment not ending
4in a break statement) must be explicitly commented as having been intended.
5All “magic numbers” should be avoided — define a constant.
6Explicitly initialize all variables before use, except where the nature of the platform’s memory
7management makes it unnecessary (and explicitly comment the absence of initialization in such
8cases).

10 Always declare the return type of functions – if the function returns nothing, use void rather
11than allowing the compiler to default to int.

12Always use the types provided by globally available typedefs (such as word8, word16,
13word32, int8, int16, int32, and boolean) rather than built-in types.

14All functions that can return an error status should be checked for an error return or explicitly ig-
15nored (i.e., casting the return value to (void)).
16Use NULL or ‘\0’ rather than 0 where appropriate.
17Avoid implicitly comparing against NULL or 0 in conditional tests:
18 if ( x != 0 )

19is preferable to
20 if ( x )

21but note that boolean values are testable in and of themselves. For instance:
22 boolean is_okay = TRUE;
23 . . .
24 if ( is_okay )
25 {
26 . . .

27is acceptable because it mirrors the use of boolean terms in natural language. There is little need
28for redundancy such as if ( is_okay == TRUE ). It is, however, important to limit such
29forms to actual boolean values and not make implicit use of the C language’s evaluation of math-

30ematical zero or end-of-string null character as being false (as noted above).

31Any local variable definition should appear within the smallest scope that includes all its uses.
32Try to (re)initialize variables near code that depends on an initialization value.
33Where practical, return from a function at the end of the code only. An exception should be made
34for argument validation – please return immediately.

110KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1111 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 19
112

1Explicit type casts should be viewed with some skepticism; a more appropriate type is often
2available and provides greater consistency throughout a variable’s scope. The same concern ap-

3plies to use of void pointers.

4Conditional expressions (? :) should be very simple.


5Never use embedded assignments ( a = b = c = d = 0 ).
6Avoid using typedefs for pointer types.
7

113KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1141 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 20
115

1 7 Revision History

3 Table 1. Revision History


Version Date Description
0.01 Initial revision
0.02 5/9/2003 Changed the conventions to fit with qct code.
0.03 5/12/2003 Further convention updates.
0.04 5/27/2003 Added new sections pertaining to code templates.
1.0 8/05/2003 Approved
1.1 8/20/2003 Added Appendix C – Auto Syntax Expansion
1.2 9/11/2003 Added section for macros

116KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1171 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 21
118

1 Appendix AFile Templates

2A.1 Header File (.h)


3 #ifndef TEMPLATE_H
4 #define TEMPLATE_H
5 /*====*====*====*====*====*====*====*====*====*====*====*====*====*====*====*
6
7 T E M P L A T E H E A D E R F I L E
8
9 DESCRIPTION
10 Give a good description here. A re-cap of the .c file
11
12 Copyright (c) 2003 by Kyocera Wireless Corp. All Rights Reserved.
13 *====*====*====*====*====*====*====*====*====*====*====*====*====*====*====*/
14
15
16
17 /*===========================================================================
18
19 INCLUDE FILES FOR MODULE
20
21 List all necessary header files here. System header files use <>, our
22 header files, use "".
23
24 Include any header files necessary to resolve all reference in this
25 header file. Don't worry about resolving stuff in the .c source file,
26 let it include what it needs.
27
28 ===========================================================================*/
29 #include <stdio.h>
30 #include "target.h"
31
32 /*===========================================================================
33
34 DATA DECLARATIONS
35
36 Declare any data (macros, structs, variables) that this module
37 (and it's source file) conceptually owns, that are used in any other module.
38
39 ===========================================================================*/
40 #define TEMPLATE_FLAG_VALUE1 0x0001 // description
41 #define TEMPLATE_FLAG_VALUE2 0x0002 // description
42 #define TEMPLATE_FLAG_VALUE3 0x0004 // description
43 #define TEMPLATE_FLAG_VALUE4 0x0008 // description
44
45 /*---------------------------------------------------------------------------
46 Separate areas of declarations using this type of comment.
47 ---------------------------------------------------------------------------*/
48 extern int2 template_cp_timer; // description
49
50 /* description of struct */
51 typedef struct
52 {
53 int2 Timer; // description
54 SomeType Variable; // description
55 } template_StructName;
56
57
58

119KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1201 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 22
121

1 /*===========================================================================
2
3 EXTERNAL FUNCTION DECLARATIONS
4
5 Declare any functions that this module (and it's source file) conceptually
6 owns, that are used in any other module.
7
8 ===========================================================================*/
9
10
11
12 /*===========================================================================
13 Basically, copy this description from the source file. You may need to
14 expand this a bit more, since they won't see the code and other source
15 file functions here in the header file.
16
17 FUNCTION TEMPLATE_FUNCTION_NAME
18
19 DESCRIPTION
20 Obviously, a description of the function goes here. Please,
21 pretty please with a cherry on top, I'm begging you, make this a good
22 description. Don't assume you'll be the only one working on it. Most likely
23 it will be some new person who's never even talked to you, who's trying to
24 fix it for an urgent CR that has to get done by noon, who'll have to figure
25 out what this function is supposed to do. Write the description for them.
26
27 DEPENDENCIES
28 List any dependcies here or "None".
29
30 RETURN VALUE
31 What does this return? If it returns just a few values, list them and when
32 it would return them.
33
34 e.g.
35 TRUE - If nv item #3 has a value.
36 TRUE - If the phone is in idle state
37 FALSE - We are roaming
38
39 The next state to be processed.
40
41 SIDE EFFECTS
42 List the other random variables your code affects, or the other functions
43 you call to secretly change things.
44
45 ===========================================================================*/
46 extern ReturnType template_FunctionName // this function name must begin with the name
47 // of this file if it is to be externalized
48 (
49 ParmType1 ParmName1, // description of Parm1
50 ParmType2 ParmName2 // description of Parm2
51 );
52
53 #endif // TEMPLATE_H

54A.2 Source File (.c)


55 /*====*====*====*====*====*====*====*====*====*====*====*====*====*====*====*
56
57 B R I E F T I T L E O F F E A T U R E
58
59 GENERAL DESCRIPTION
60 Give a good description of what this source file is doing.
61
62 EXTERNALIZED FUNCTIONS
63 List all extern functions. They must begin with the name of this file.
64
65 template_Init
66 Brief description of this function
67 Initializes variable, must be called first.

122KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1231 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 23
124

1 template_Close
2 Cleans up all variables used in these functions. Must call last.
3
4 INITIALIZATION AND SEQUENCING REQUIREMENTS
5 Any requirements, list here.
6 Must call template_Init() before any other function in this module.
7 Must call template_Close() after you're all done w/ this stuff.
8
9 Copyright (c) 2003 by Kyocera Wireless Corp. All Rights Reserved.
10 *====*====*====*====*====*====*====*====*====*====*====*====*====*====*====*/
11 // Note: 3 blank lines between sections here
12
13
14
15 /*===========================================================================
16
17 INCLUDE FILES FOR MODULE
18
19 List all necessary header files here. System header files use <>, our
20 header files, use "".
21
22 ===========================================================================*/
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include "target.h"
26 #include "task.h"
27 // Note: 3 blank lines between sections here
28
29
30
31 /*===========================================================================
32
33 LOCAL DEFINITIONS AND DECLARATIONS FOR MODULE
34
35 This section contains local definitions for constants, macros, types,
36 variables and other items needed by this module.
37
38 Place a comment for a description of the variable immediate after it, if
39 enough room on line, or on the following line.
40
41 ===========================================================================*/
42 /* Maximum search rates - This is the old 1X throttle
43 before the 8X mode testing was done. Note that during
44 8X mode testing these were lowered by 30 Hz. */
45
46 static int2 srch_rate_upper_limit = 130; // Hz
47 static int2 srch_rate_lower_limit = 120; // Hz
48
49 /*---------------------------------------------------------------------------
50 Separate areas of declarations using this type of comment.
51 ---------------------------------------------------------------------------*/
52 // Defines to support the proper dynamic throttle action
53 #define SRCH_RATE_UPPER_LIMIT ( srch_rate_upper_limit - srch_limit_rate_backoff \
54 - srch_limit_chip_backoff )
55 #define SRCH_RATE_LOWER_LIMIT ( srch_rate_lower_limit - srch_limit_rate_backoff \
56 - srch_limit_chip_backoff )
57
58 /*---------------------------------------------------------------------------
59 Separate areas of declarations using this type of comment.
60 ---------------------------------------------------------------------------*/
61 // Keeps track of the current state of the Searcher Task state machine.
62 srch_state_enum_type srch_state = SRCH_START_STATE;
63
64 // Parameters that control the behavior of the searcher task.
65 // These are settable by the base station via MCC
66 srch_parm_struct_type srch_parms;
67 // Note: 3 blank lines between sections here
68
69
70
71 /*===========================================================================

125KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1261 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 24
127

1
2 FUNCTION TEMPLATE_FUNCTION_NAME
3
4 DESCRIPTION
5 Obviously, a description of the function goes here. Please,
6 pretty please with a cherry on top, I'm begging you, make this a good
7 description. Don't assume you'll be the only one working on it. Most likely
8 it will be some new person who's never even talked to you, who's trying to
9 fix it for an urgent CR that has to get done by noon, who'll have to figure
10 out what this function is supposed to do. Write the description for them.
11
12 DEPENDENCIES
13 List any dependcies here or "None".
14
15 RETURN VALUE
16 What does this return? If it returns just a few values, list them and when
17 it would return them.
18
19 e.g.
20 TRUE - If nv item #3 has a value.
21 TRUE - If the phone is in idle state
22 FALSE - We are roaming
23
24 The next state to be processed.
25
26 SIDE EFFECTS
27 List the other random variables your code affects, or the other functions
28 you call to secretly change things.
29
30 ===========================================================================*/
31 ReturnType template_FunctionName // this function name must begin with the name
32 // of this file if it is to be externalized
33 (
34 ParmType1 ParmName1, // description of Parm1
35 ParmType2 ParmName2 // description of Parm2
36 )
37 {
38 /* work your magic in here, make the world a better place, save the day
39 or at least, make my phone do neat things */
40
41 /* LOGIC: For anything more complex than trivial addition give a few sentences
42 describing what you're doing, the logic you're using, and, most importantly,
43 why you're doing this. This way when someone is trying to figure out what the
44 heck is going on in your function they, at least, start with an idea of how
45 you're going about it. */
46
47 /*-------------------------------------------------------------------------
48 Sample statement layouts
49 -------------------------------------------------------------------------*/
50 // If statement. Even one line expressions must have braces around it
51 if ( Variable == Value )
52 {
53 i++;
54 }
55 else if ( ( Variable == Value ) &&
56 ( Test == Condition ) || MyStruct.Field > OtherStruct.Setting ) )
57 {
58 // ...
59 }
60 else
61 {
62 // ...
63 }
64
65 // Switch statement example
66 switch ( Choice )
67 {
68 case Choice = 1:
69 i++;
70 break;
71

128KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1291 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 25
130

1 case Choice = 2:
2 j++;
3 // fall through <-- explicitly state this
4
5 case Choice = 3:
6 k++;
7 DoSomething( ParmName1, ParmName2 );
8 break;
9
10 default:
11 ErrorMessage( MyMessage );
12 }
13
14 // for loop example
15 for ( int iIndexIntoNameList = 0; iIndexIntoNameList <= NameList.Length;
16 iIndexIntoNameList++ )
17 {
18 // ...
19 }
20
21 }
22
23
24
25 /*
26 Remember, no <TAB> characters. Use spaces. Set up your editor to use <space>.
27 Violators will be taken into the back room with a wet noodle and beatings
28 will ensue.
29
30 We are using an indent level of 2 spaces. I know, I know, you like 3 spaces,
31 and you there, in the back, you like 4, you Microsoft junkie you. And you over there
32 in the blue shirt you like using 8, 'cause that's what a real man/<TAB> would
33 use. Well, we're using 2 here in this shop, just set it up in your editor
34 settings and forget about it. And if you really don't like it ....
35 'indent -i2 myfile.c -o newfile.c'
36
37 Stick 3 blank lines between coding sections, this just helps to set them off.
38 */

131KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1321 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 26
133

1 Appendix BReligious War – Tabs vs Spaces

2Ah, the subject of many conversations. Usually, with the end result of people storming out of the
3room with murderous looks upon their faces as they race off to their colleagues desk chairs to
4plant thumbtacks upon them.

5There is a lucid article about this subject on Jamie Zawinski’s site (he of the first version of Nets-
6cape fame) http://www.jwz.org/doc/tabs-vs-spaces.html. Go on read it, it only takes three
7minutes to read and I’ve got time before my next meeting. I’ll wait.

8Ok, I bet none of you actually read that. Oh well, his main point is that we use the word “tab” to
9mean different things: 1) how the code is indented; 2) how your editor reacts to an actual TAB
10character (0x09) in a file; 3) how your editor reacts to you pressing the <TAB> key on your key-

11board.

12Point 1, how the code is indented. This, is how many columns your code is indented. Two, three
13and four are all very common numbers for this. Some people use a more complicated method de-

14pending on a variety of context rules.

15Point 2, how your editor reacts to reading a TAB character in a text file. In days gone by, on Unix
16system, dumb terminals, emacs, vi, etc… the tradition has been for a TAB character to mean,

17“move to the right until the current column is a multiple of 8”. Windows and Macintosh OSes do

18essential the same thing, except they use a multiple of 4. This is usually configurable by any cur-

19rent text editor.

20Point 3, what happens when you hit the <TAB> key. Some editors insert a TAB character (0x09)
21just like they would an ‘a’, ‘b’, or ‘c’. It then gets displayed on the screen according to Point 2,
22above. Some editors move your cursor over a certain number of spaces until you hit a multiple of

238 (or whatever). Some editors insert a number of SPACE (0x20) characters as defined in their

24configuration somewhere.

25Point 1 is the religious war. Points 2 and 3 are user interface and operability issues.
26Now that Jamie has helped us get our terms defined, let’s move on to our point.
27The big point to all this is that we all want the code we’re working on to look pretty, to line up, to
28be indented in a consistent manner. A SPACE character (0x20) is consistent, a TAB character
29(0x09) is not, taking on meanings of any multiple of 2, 4, or 8 columns. This becomes especially

30evident when TAB characters are used throughout a line, not just in the beginning.

31Below is a code fragment illustrating what I mean. This uses <TAB> characters, and the editor is
32set to display <TAB> characters on column lines of multiples of 4.

134KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1351 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 27
136

1 void cm_task ( dword dummy )


2 {
3 static rex_sigs_type sigs; /* hold signals */
4 cm_cmd_s_type *cmd_ptr; /* command pointer */
5 cm_inband_cmd_s_type *inband_cmd_ptr; /* inband one */
6 cm_inband_cmd_info_s_type *cmd_info_ptr; /* info block */
7
8 cm_init(); /* initialize queues */
9
10 for( ;; ) /* Wait on REX, forever */
11 {
12 sigs = rex_wait( CM_RPT_TIMER_SIG
13 | CM_TIMER_SIG
14 | CM_RSSI_TIMER_SIG );
15
16 if( sigs & CM_RPT_TIMER_SIG ) /* call watchdog. */
17 {
18 cm_kick_dog();
19 }
20 } // for(;;)
21 }

22This is all nice and lined up, now let’s look at the same code with our editor set to display the
23<TAB> character in a multiple of 2 columns:
24 void cm_task ( dword dummy )
25 {
26 static rex_sigs_type sigs; /* hold signals */
27 cm_cmd_s_type *cmd_ptr; /* command pointer */
28 cm_inband_cmd_s_type *inband_cmd_ptr; /* inband one */
29 cm_inband_cmd_info_s_type *cmd_info_ptr; /* info block */
30
31 cm_init(); /* initialize queues */
32
33 for( ;; ) /* Wait on REX, forever */
34 {
35 sigs = rex_wait( CM_RPT_TIMER_SIG
36 | CM_TIMER_SIG
37 | CM_RSSI_TIMER_SIG );
38
39 if( sigs & CM_RPT_TIMER_SIG ) /* call watchdog. */
40 {
41 cm_kick_dog();
42 }
43 } // for(;;)
44 }

45See how that’s no longer lined up all nice and pretty. The declaration of variables no longer line
46up. The comment lines neither. The flags in the rex_wait function don’t line up with the first

47flag anymore.

48You might be saying, well, if you only use <TAB> characters at the beginning of a line that’s not
49a problem. Quite true, but most people are going to use the <TAB> key to line things up past the
50beginning of a line instead of the <SPACE> key. This then puts a <TAB> character in the middle

51of a line and we’re back to ugly formatting again.

52Further, when you go to print this code, many printers have their own meaning for the <TAB>
53character, sometimes 8 spaces, sometimes lining it up on columns that are multiples of 8.
54In short, the <TAB> character just means too many different things, depending on what applica-
55tion you’re using to view or print the code. We looked at many other style guidelines, since this
56is an issue that concerns most people with the fervor of the “Tastes Great! Less Filling” debate.

57The majority of these guides advocate using the <SPACE> character and not the <TAB> charac-

58ter.

137KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1381 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 28
139

1Hence we have mandated that there will be no, repeat no, <TAB> characters in the source code.
2You can setup your editor (MSVS++, vim, emacs, slickedit, etc…) so that when you hit the

3<TAB> key, it will indent it to the right indentation level, and use <SPACE> characters to do so.

140KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1411 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 29
142

1 Appendix CAuto Syntax Expansion

2Most commercial IDEs supports configurable syntax expansion. Based on this document, KWC
3coding standard team has developed syntax expansion triggers for two popular IDEs among
4KWC developer: Visual Studio (Version 6.0) and Visual SlickEdit (Version 8.0).

5The idea is to link a “trigger” – a simple keystroke sequence with a macro (Visual Studio) or an
6alias (Visual SlickEdit) which expands predefined code blocks or file templates into the source
7code file being edited.

8Using auto syntax expansion not only speeds up coding process, but also enforces the coding
9standard. Section C.1 lists all the syntax expansion triggers being implemented at this point.
10Section C.2 and C.3 explain how to setup the syntax expansion in Visual Studio (Version 6.0)

11and Visual SlickEdit (Version 8.0).

12Please note a trigger ends with backslash (‘\’) in Visual Studio and space (‘ ‘) in Visual SlickEdit.

13C.1 Auto Syntax Expansion Triggers


14 File templates
Visual Studio Visual SlickEdit Expand to
“src\” “src ” C source (.c) file template (§3)
“hdr\” “hdr ” C header (.h) file template ( §3)

15 Comment blocks
Visual Studio Visual SlickEdit Expand to
“ssh\” “ssh ” C source (.c) file comment header (§3.2.1, §A.2)
“ffh\” “ffh ” C header (.h) file comment header (§3.1.2, §A.1)
“fch\” “fch ” C function comment header (§3.2.3, §A.1)
“bc\” “bc ” C-Style comment block (§5)

16 Function templates
Visual Studio Visual SlickEdit Expand to
“func\” “func ” C Function declaration template (§4.9)
“re\” “re ” C “return;” statement

17

18

19 Typedef data structures

143KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1441 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 30
145

Visual Studio Visual SlickEdit Expand to


“tys\” “tys ” C “typedef” a struct type (§2.7)
“tye\” “tye ” C “typedef” an enum type (§2.6)
“ty\” “ty “ C “typedef” keyword (§2.5)

20 Controlled block - if
Visual Studio Visual SlickEdit Expand to
“if\” “if ” C “if” block
“ife\” “ife ” C “if-else” block
“eli\” “eli ” C “else if” block
“el\” “el “ C “else” block

21 Controlled block - switch


Visual Studio Visual SlickEdit Expand to
“sw\” “sw ” C “switch” block (§4.2)
“ca\” “ca ” C “case-break” block
“de\” “de “ C “default-break” block
“br\” “br “ C “break;” statement

22 Controlled block - loop


Visual Studio Visual SlickEdit Expand to
“fo\” “fo “ C “for” loop
“wh\” “wh “ C “whole” loop
“dwh\” “dwh “ C “do-while” loop
“br\” “br “ C “break;” statement
“con\” “con “ C “continue;” statement

23 Preprocessor - #if
Visual Studio Visual SlickEdit Expand to
“3if\” “3if “ “#if - #endif” block
“3ife\” “3ife ” “#if - #else - #endif” block
“3ifd\” “3ifd “ “#ifdef - #endif” block
“3ifn\” “3ifn “ "#ifndef - #endif" block
“3e\” “3e “ "#else"
“3ei\” “3ei “ “#elif"

24

25

26

27 Preprocessor - #define

146KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1471 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 31
148

Visual Studio Visual SlickEdit Expand to


“3d\” “3d “ #define a constant (§2.4)
“3de\” “3de “ #define a macro with parameters (§2.4)
“3u\” “3u ” #undef

28 Preprocessor - others
Visual Studio Visual SlickEdit Expand to
“3i\” “3I “ #include <\^.h>
“3er\” “3er ” #error
“3p\” “3p “ #pragma

29 KWC integral types


Visual Studio Visual SlickEdit Expand to
“i32\” “i32 “ “int32” – signed long int
“i16\” “i16 “ “int16” – signed short
“i8\” “i8 “ “int8” – signed char
“u32\” “u32 “ “uint32” – unsigned long int
“u16\” “u16 “ “uint16” – unsigned short
“u8\” “u8 “ “uint8” – unsigned char
“bo\” “bo “ “boolean” – unsigned char
“t\” “t “ “TRUE” – 1
“f\” “f ‘ “FALSE” – 0

149KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1501 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 32
151

1C.2 Visual Studio Setup


2 Assume Visual Studio is installed in directory “C:\Program Files\Microsoft Visual Studio”;
3 Obtain the VBScript macro file “TemplateCompletion.dsm” (from Perforce:
4 //depot/QCPS/QA/). Follow the steps below:
51. Copy the file “TemplateCompletion.dsm” to directory: "C:\Program Files\Microsoft Visual
6 Studio\Common\MSDev98\Macros"
72. Launch Visual Studio, open "Tools | Customize" dialog.
83. On this dialog, select "Add-ins and Macro Files" tab, turn on "TemplateCompletion" item
9 in list.
104. On the same dialog, select the "Keyboard" tab, set "Category" to "Macros" and "Editor" to
11 "Text", link "CompleteTemplateBackSlash" command with "\" keystroke (backslash),
12 link "ToggleTemplateCompletion" command with "Ctrl + \" keystroke. (Note: if the com-
13 mands do no show up, just close and re-open this dialog. VS++, in some cases, needs to re-
14 fresh itself.)

165. Close the dialog. Open a C file (.c or .h), type in “fo\”. It should be expanded into a for loop
17 block like this:
18 for ( ; ; )
19 {
20 }

216. To toggle on/off syntax expansion, press "Ctrl + \" keystroke.

152KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1531 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 33
154

1C.3 Visual SlickEdit Setup


2 Assume Visual SlickEdit is installed, and the user configure directory is “C:\Documents and
3 Settings\username\My Documents\My Visual SlickEdit Config”. Obtain the VS alias file
4 “c.als” (from Perforce: //depot/QCPS/QA/). Follow the steps below:
51. Copy file “c.als” to directory: “C:\Documents and Settings\username\My Documents\My
6 Visual SlickEdit Config”
72. Launch Visual SlickEdit, open "Tools | Configuration | File Extension Setup " dialog
83. On this dialog, select "c” extension; select “General” tab.
94. Verify that “c.als” is shown in “Alias filename:” field, if not type it in.
105. Click on the “Aliases…” button and verify that the all the aliases are defined.

6. Close the dialog by clicking OK. Open a C file (.c or .h) type in “fo ” (space after fo). It
11

12 should be expanded into a for loop block.

155KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1561 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 34
157

1 Appendix DRobust Function Format

2D.1 Description
3This document describes the robust function format we should use for our standard and higher
4level methods. It is a time tested and proven way to eliminate bugs early in the development

5cycle and is the standard way we should write our methods.

6Pros: Produces Robust, Self-Debugging, and Highly Maintainable code.


7Cons: Additional Development Time (early in the cycle), Less Efficient code.

8D.1.1 Speed -> Robustness Tradeoff


9The first thing to note is that this function format exchanges speed for robustness. It is best used
10in higher level code that does not bear the necessity of being highly optimized but does bear the

11necessity of being easily debugged and robust.

12D.1.2 ‘Helper’ Function Exception


13As this format requires significant overhead it does not apply to internal (non-exported) helper
14methods- which we will define as small roughly 10 line methods mainly used as generic tools
15that don’t really have a need to return errors or do robust input validation. Examples of such

16would be translation methods used to convert a byte to its ASCII hex representation, or boolean

17methods used to do simple generic input validation (IsInitialized, IsValidDateTime,etc).

18

19D.2 Function Format

20D.2.1 Before we Begin: Embrace Paste & Replace


21This method of defining functions requires significant overhead, which would be a pain and
22quite time consuming to retype every time you create a method. The best way to make this pro-
23cess as painless as possible is to create a template and just paste the template into your code and

24do a find/replace on the typical terms.

158KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1591 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 35
160

1D.2.2 Function Comments


2The current method of function comments is quite acceptable with a few minor modifications.
3An Example for the InsertString Method
4
5 /*===============================================
6 FUNCTION InsertString
7
8 DESCRIPTION
9 Inserts a string to the widget’s data buffer. If the string is
10 too large to fit will insert as many characters as possible.
11
12 ARGUMENTS
13 this
14 IN: Pointer to the text widget into which you are inserting. Must be
15 Non-NULL and must be initialized.
16
17 strInput
18 IN: The string to be inserted. Must be Non-NULL and contain only
19 ASCII characters and digits.
20
21 uiLocation
22 IN: The zero indexed location of where the string should be inserted.
23 Should be within the bounds of the text buffer as given by
24 GetMaxCharacterCount()
25
26 RETURNED STATUS CODES:
27 SCS_SUCCESS: The string was successfully inserted.
28 SCS_WIDGET_TEXT_INSERT_PARTIAL: the string was too large to fit so it
29 was only partially inserted.
30 SCS_WIDGET_TEXT_INSERT_NONE: there is no room remaining in the buffer
31 so no characters were inserted.
32 SCE_MODULE_UNINITIALIZED: ‘this’ points to an uninitialized text widget
33 SCE_UNEXPECTED_NULL_PARAMETER: ‘this’ or ‘strInput’ was NULL
34 SCE_INDEX_OUT_OF_BOUNDS: uiLocation was past the end of the buffer
35 ================================================*/

36D.2.2.1 FUNCTION
37Copy and paste the name of the function.

38D.2.2.2 DESCRIPTION
39Enter a description of the unique behavior of this function and provide information about any
40special cases.

41D.2.2.3 ARGUMENTS
42Copy and paste the arguments from the function declaration. Give a description of the purpose
43(eg: The string to be inserted ) of the argument followed by rules on valid input (eg: Must be
44Non-NULL and contain only ASCII characters and digits.)

45D.2.2.4 RETURNED STATUS CODES


46Give a list of any status codes the function returns and a description of what each status code sig-
47nifies for this particular function.

161KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1621 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 36
163

1D.2.3 Function Declaration


2 StatusCode_t InsertString( IN uitextwidget *this,
3 IN uitext_type *strInput,
4 IN unsigned int uiLocation )

5D.2.3.1 Return Value


6Every function written in this robust format should return a statuscode_t. No exceptions.

7D.2.3.2 Variable Direction ( IN, OUT, OWN defines)


8The terms IN and OUT and OWN will be defined to nothing (whitespace) and will be used only
9as visual descriptors to signify whether or not the variable is intended to be used as IN or OUT or
10both. As we are returning all values by reference (since the actual return is reserved for

11StatusCode_t), this will be very useful in determining how the method is expecting to use the

12parameter.

13

14• OWN Signifies that a pointer’s ownership (ownership = who needs to free the memory)
15 will change upon the successful return of a function – MUST be preceded by IN_ or OUT_.
16 See section Error! Reference source not found. for error returns. Note that having a pointer
17 change ownership is NOT recommended and should only be used in extreme cases.
18

19• IN Signifies that the parameter’s value is (or may be) used.
20• OUT Signifies that the parameter’s value will (or may) be set by the method.
21• IN_OUT Signifies that the variables value is (or may be) used, as well as the value will (or
22 may) be set.
23• IN_OWN Signifies that a pointer allocated by the caller changes ownership to the called
24 function; The calling function should immediately set any local references to the pointer to
25 NULL to avoid using a pointer owned.
26• OUT_OWN Signifies that a pointer allocated by the called function changes ownership
27 to the caller after a successful return.
28

29Note: The Called Function always OWNs the memory in an error case
30If the called function returns an ‘error status’ then it is the CALLED function’s responsibility to
31free all pointers modified by the IN_OWN or OUT_OWN keywords. It is Never the calling func-

32tion’s responsibility to free variables marked with the OWN keyword if the status code returned

33by the calling function was an error.

164KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1651 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 37
166

1D.2.4 Function Body


2This is, of course, the most important part of the Robust Function Format. Although parts may be
3tedious, rest assured that the end result is worth it. Functions will be divided up into five main
4sections: Variable Initialization, Input Validation, Functional Logic, Output Validation, and

5Cleanup.

6D.2.4.1 Variable Initialization


7This includes local variables as well as parameters marked OUT!!

8Primitive Variables

9All primitives (ints, floats, doubles, etc.) should be initialized to 0.

10Pointers

All Pointers Must be initialized to NULL. This allows us to check in the cleanup portion of the
11

12code for any non-NULL pointers and free them. If you free a pointer during the Functional Logic

13portion for any reason, ensure that you immediately set it to NULL to avoid freeing a free’d

14pointer.

15D.2.4.2 UICALLOC Not UIMALLOC


16Always use UICALLOC rather than UIMALLOC even if you are about to assign and use up the
17entire contents of the allocation. If the buffer is to hold a string it conveniently ‘null terminates’
18the string in the advent the developer forgets to. If the buffer is for a structure it zero’s out the

19padding bytes so a bit by bit comparison of the entire structure in memory (commonly using the

20‘sizeof’ operator and memcmp) does not fail due to the commonly forgotten padding bytes. By

21getting into the habit of always using UICALLOC it makes the usage natural and does not rely

22on the developers ‘intuition’ on when to use it or not.

23D.2.4.3 Arrays & Structures


24A convenient feature of many c/c++ compilers (including arm) is that if you assign {0} to an ar-
25ray during declaration it will zero out the entire body of the array. Thus all arrays should be ini-
26tialized to 0. As Local structures should always be zeroed to ensure the padding is zeroed as well

27as the data.

28Ex:
29int intarray[100] = {0}; struct mystruct = {0};
30

31(Both of these statements will zero the entire data allocated, not just the first item.)

167KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1681 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 38
169

1D.2.4.4 Status Code (Return Variable)


2Rather than directly returning the status code constants (SCS* SCE*) directly, in every method a
3status code variable should be declared and initialized to a value (preferably SCS_SUCCESS.)
4This variable should be assigned the status code and returned.

5D.2.4.5 Notes on Optimization


6You’ll note that every variable is being assigned the value 0, this allows the compiler to do one
7large blanket zero operation on all the variables in the local stack.

8D.2.4.6 Input Validation


9All input (parameters) to a function should be validated before reaching the functional logic por-
10tion.

D.2.4.7 Primitive Values


11

12Primitive values should always be checked to be within proper bounds as defined by their pur-
13pose. For Example: in the case of an index into an array the primitive should be checked to be

14within the array boundaries. If the input is supposedly an enumeration check to make sure the

15value is a valid enumeration value.

16D.2.4.8 Pointers
17‘IN’ and ‘IN OUT’ Pointers should be checked to be Non-NULL. If it is legal for an incoming
18pointer to be NULL please place a comment in the initialization section declaring that you’re in-
19tentionally not checking an input pointer for NULL and give the reason why.

20D.2.5 Functional Logic


21This section is going to be the hardest to swallow for those of us who are used to the “goto is
22evil” backlash caused by Dijkstra’s 1968 article “Go To Statement Considered Harmful.” Even in

23our C coding standard they claim that goto is never appropriate. Hopefully without bringing up a

24flame war . . . they’re wrong . As you shall see there are cases where goto is appropriate and

25generates more maintainable, robust, and easier-to-follow code.

26D.2.5.1 ONE ‘return’ statement for each method


27The goal is to have functions that have one entry and one exit point. That way memory alloca-
28tion/deallocation is greatly simplified, debugging is easier due to the linear nature of the method,

29and program flow is more natural to follow. This can only be accomplished by having one (and

30only one) return statement.

31

170KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1711 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 39
172

1D.2.5.2 NULL as you go!


2If you give an allocated pointer to someone else (of course using the OWN keyword) OR free an
3allocated pointer before you reach the Cleanup section, always (immediately) set that pointer to
4NULL... EVEN if you are about to immediately assign it a new value. In the future if someone is

5modifying your function and ends up adding code in between the free and the new allocation this

6will stop them from accidentally using an already free’d value. As well it protects against the

7situation where you may have a double free when it is checked for NULL and free’d again in the

8cleanup section.

9It is also acceptable to assign the pointer to NULL on the same line that you free’d the pointer- to
10further enforce the fact that it is an atomic operation. Ex:
11 free ( p ); /* This is ok */
12 p = NULL;

13-or -
14 free( p ); p = NULL; /* This is also ok */

15

16D.2.5.3 Go directly to labels, don’t fall through!


17You’ll note in the following example there are two cases where the goto appeared ‘unnecessary’
18(goto Success: and the following goto Cleanup:) since the code fall through would have had the
19same effect. As with most other quirks of this format this was done with maintenance in mind:

20(1) If the goto success: was not there, in the future if someone added additional code after the ‘if-
21 else if’ statement, processing if 3 == *B for example, they would have to go back, read, and
22 understand your code in order to realize that you intended to finish the function logic and ter-
23 minate in the success case. Reading and understanding seemingly unrelated code is a time
24 consuming and error prone process that should be avoided.
25(2) As well if they added an additional Success Label (perhaps to do some special processing
26 such as output a Cait debug string) under your Success label they would have to once again
27 read and understand your code in order to realize they needed to add a ‘goto Cleanup:’ to
28 avoid falling through to their success case.

29D.2.6 Error Handling


30All error handling should be done at the Error: label. You should always ASSERT to ensure that
31the StatusCode_t being returned was set to an error type (this helps catch cases where people
32‘goto’ an error label without setting the status variable.) For different error handling it is accept-

33able to have several error labels which all branch to the main error label. Note that in an error

34case you MUST free all pointers modified with the OWN keyword in the Error section!

35D.2.7 Output Validation (Success Case)


36First ASSERT to ensure that the StatusCode_t being passed back is set to a success type. In the
37case where you are going to return a successful StatusCode_t the output should always be valid-
38ated to ensure it is within the correct bounds- eg: if you are passing back a Date, assert the Date

173KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1741 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 40
175

1is valid; if you are passing back an index into a buffer, assert the index is within the range of the
2buffer. This helps to catch mistakes made during the initial creation of the method, as well as

3later on when hurried changes are made in response to a CR.

4D.2.8 Cleanup
5All cleanup (excluding freeing of OWN’d variables in an error case) should be done at the
6Cleanup label. All Non-Null pointers (allocated in this function) should be freed. Note it is ac-
7ceptable not to set the pointers to NULL here after freeing them since Cleanup should always be

8the last thing done before the method returns.

9D.3 ‘THE’ example


10 StatusCode_t DoSomething ( IN char *A, OUT int *B )
11 {
12 StatusCode_t scStatus = SCS_SUCCSS;
13 Char *pStr1 = NULL;
14 Char *pStr2 = NULL;
15
16 if ( NULL == A ) // Ensure IN parameter is Non-NULL
17 {
18 scStatus = SCE_UNEXPECTED_NULL_PARAMETER;
19 goto Error;
20 }
21
22 if( NULL == B ) // Ensure OUT parameter is Non-NULL
23 {
24 scStatus = SCE_UNEXPECTED_NULL_PARAMETER
25 goto Error;
26 }
27 *B = 0;
28
29 pStr1 = (char*) calloc( 64 );
30 if ( NULL == pStr1 )
31 {
32 scStatus = SCE_OUT_OF_MEMORY;
33 goto Error;
34 }
35
36 pStr2 = (char*) calloc( 128 );
37 if ( NULL == pStr2 )
38 {
39 // Note that if this was a return we would have to free pStr1
40 scStatus = SCE_OUT_OF_MEMORY;
41 goto Error;
42 }
43
44 *B = strncpy( pStr2, A, 128 );
45 *B += strncpy( pStr1, pStr2, 64 );
46
47 if ( 0 == *B )
48 {
49 scStatus = SCE_CUSTOM_ERROR;
50 goto Error;
51 }
52 else if ( 2 == *B )
53 {
54 scStatus = SCS_CUSTOM_SUCCESS;
55 goto Success;
56 }
57
58 //----------------------------------------------------- success
59 success:
60 ASSERT( SM_SUCCESS( scStatus ) ); // Ensure returning a successful status

176KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1771 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 41
178

1 ASSERT( *B > 0 ); // Validate the output


2 goto cleanup:
3
4 //----------------------------------------------------- cleanup
5 cleanup:
6 if ( NULL != pStr1 ) { free( pStr1 ); }
7 if ( NULL != pStr2 ) { free( pStr2 ); }
8 return scStatus;
9
10 //----------------------------------------------------- error
11 error: // An error occurred
12 ASSERT( SM_ERROR( scStatus ) ); // Ensure returning an unsuccessful status
13 // DO ADVANCED ERROR HANDLING
14 goto Cleanup:
15
16 }

179KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1801 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 42
181

1 Appendix EGeneric Status Codes

2E.1 Bitwise Breakdown


3Status codes are a 32 bit UNSIGNED INTEGER broken up into three sections
4

Bit(s)* Description N
29-31 Reserved for Future use 8
21-28 Group Code (eg: SG_MESSAGING) 256
12-20 Sub-Group Code (eg: SB_ MESSAGING_MMS) 512
1-11 Specific Sub Codes 2048
0 Status Type (1 indicates successful status, 0 indicates a failed (unsuccessful) 2
status)
5* Bits are numbered with 31 being the most significant bit to 0 being the least significant bit

6E.2 Group Codes


7Group codes are meant to categorize the status codes by a higher level filter, such as a set of
8common related modules for a large feature. Examples of higher level organizations would be
9Widgets, Messaging, Brew, Call Processing, etc. Group Codes are prefixed with SG. For the wid-

10get group the code would be SG_WIDGET.

E.3 Sub-Group Codes


11

12Sub-Group codes are meant to categorize status codes at a finer, more module specific, level.
13Under the Widgets Group some potential sub groups would be text, picture, and forms. Under the
14Messaging Group some potential subgroups would be Message Creation, Message Viwing, Mes-

15sage Sending, Message processing, etc. Sub-Group codes are prefixed with SB followed by the

16name of the parent group. For the Text Widget, who is a member of the widget group, the format

17would be: SB_WIDGET_TEXT.

182KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1831 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 43
184

1E.4 Sub Codes


2Sub Codes indicate custom errors/successes. They should be prefixed with SCS for successful
3statuses, SCE for error status, followed by the name of the Group and SubGroup.

4E.4.1 Text Widget Example:


5The StringAppend method of the text widget may return a generic SCS_SUCCESS to indicate
6the append executed flawlessly. However there are three potential cases that could also occur:

7Only a portion of the string was able to be appended before the data buffer ran out of space.

8None of the string was able to be appended since the buffer was already at capacity. Or, the ap-

9pend failed due an internal error reason.

10The StringAppend method could return SCS_WIDGET_TEXT_ APPEND_PARTIAL to indicate


that an append was only able to append some of the characters before it ran out of space. (Note:
11

12since this is an acceptable status this status code could have the StatusType set to SUCCESS)

13The StringAppend method could return SCS_WIDGET_TEXT_ APPEND_NONE to indicate


14that an append was not able to append any characters since the buffer was out of space. (Note:
15since this is an acceptable status this status code could also have the StatusType set to SUC-

16CESS)

17If the StringAppend method failed due to an out of memory condition it could could return
18SCE_OUT_OF_MEMORY. If the text passed in was null thus there were no characters to ap-
19pend it could return SCE_UNEXPECTED_NULL_PARAMETER. If it failed because the text

20widget had not been initialized it could return SCE_MODULE_UNINITIALIZED. If it failed

21due to an undefined internal append error (not allowed to append empty strings, certain charac-

22ters, etc) it could return a generic SCE_WIDGET_TEXT_APPEND_FAILED (so long as there

23were plenty of comments documenting when it would return this value.)

185KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1861 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 44
187

1E.4.2 Declaring Status Codes


2Each status code should be defined in statuscodes.h using the
3SM_GENERATE_STATUS_CODE macro. All status codes begin with the prefix SC. All status
4codes should be preceeded with a comment describing their purpose.
5 // Operation Was a Success
6 #define SCS_WIDGET_TEXT_APPEND_PARTIAL SM_GENERATE_STATUS_CODE( SG_WIDGET, \
7 SB_ WIDGET_TEXT, \
8 1, \
9 SC_SUCCESS )
10
11 #define SCS_WIDGET_TEXT_APPEND_NONE SM_GENERATE_STATUS_CODE( SG_WIDGET, \
12 SB_ WIDGET_TEXT, \
13 2, \
14 SC_SUCCESS )

15E.5 Status Macros


16There are several macros defined in statuscodes.h for the purposes of interacting with status
17codes. All status macros begin with the prefix SM.

18• SM_SUCCESS ( StatusCode )


19 Returns true if the status code is successful (ie a 0 in bit 0)
20• SM_ERROR ( StatusCode )
21 Returns true if the status code is unsuccessful (ie a 1 in bit 0)
22• SM_GENERATE_STATUS_CODE (Group, SubGroup, StatusCode, StatusType )
23 Returns a status code with the correct bit allocation
24• SM_GROUP (StatusCode)
25 Returns the group for the provided status code
26• SM_STATUSTYPE (StatusCode)
27 Returns the Status Type for the provided status code
28• SM_SUBGROUP (StatusCode)
29 Returns the sub­group
30• SM_SUBCODE (StatusCode)
31 Returns the sub code

32E.6 Why Use Generic Errors?


33• You might wonder why we would ever use generic errors- wouldn’t it be better if we returned
34 SCE_TEXT_WIDGET_OUT_OF_MEMORY so we knew the text widget was the module in
35 which the memory allocation failed? Well there are 2 good reasons…
36• Commonly generic errors need to be passed up several levels before they are handled- such
37 as out of memory errors. If each method returned its own out of memory status code- at each
38 level of the tree code would have to be added to translate from the called method’s out of
39 memory to the calling method’s out of memory status code. Really in the end the same beha-
40 vior is going to occur anyway- memory is going to be freed or the phone is going to crash.
41• More importantly, creating a bunch of specific status codes would cause a whole slew of
42 overhead each time a new method was written in order to create the ‘specific versions.’ All in
43 all it’s a waste of time and has very little gain.

188KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1891 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 45
190

2E.7 Why return status codes rather than pass by reference?


3• Avoids the case where the caller could pass an invalid/null pointer to the method. If you cant
4 return an error because there is no means to do so you have to have error handling on your
5 error handling (imagine checking your error pointer for null-ness in every case you want to
6 return an error.)
7• Avoids the case where the caller is re-using an status variable, which may already be in an er-
8 ror state, and the callee forgets to reset it to a successful value, so if the function returns nat-
9 urally without setting the status codes it will appear that the method had an error.
10• You should never use the result of a method unless it returns successfully. In reality passing
11 the status code by reference would delay processing of a value since you would have to first
12 save the (possibly invalid) result of the function call, then in a separate statement check the
13 status code to ensure it was successfull, then finally actually process the return value.
14• If you are returning the status code directly from the function you can just embed it in an ‘if’
15 statement. This allows for a natural if->good else->bad logic flow.

191KWC-SWAT TeamKWC-SWAT TeamJoshua A. Gage<DocNum> Rev. X0 8865897.doc


1921 September, 200415 October, 2003<08 May, 2003>Kyocera Proprietary Page 46

You might also like