NEC CC78K0S

User’s Manual
CC78K0S
C Compiler Ver.1.30 or Later
Language
Target Devices
78K/0S Series
Document No. U14872EJ1V0UM00 (1st edition)
Date Published January 2001 N CP(K)
©
Printed in Japan
2001
[MEMO]
2
User’s Manual U14872EJ1V0UM
Windows and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the
United States and/or other countries.
PC/AT is a trademark of International Business Machines Corporation.
i386 is a trademark of Intel Corporation.
UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open
Company Limited.
SPARCstation is a trademark of SPARC International, Inc.
SunOS and Solaris are trademarks of Sun Microsystems, Inc.
HP9000 series 700 and HP-UX are trademarks of Hewlett-Packard Company.
User’s Manual U14872EJ1V0UM
3
• The information in this document is current as of November, 2000. The information is subject to
change without notice. For actual design-in, refer to the latest publications of NEC's data sheets or
data books, etc., for the most up-to-date specifications of NEC semiconductor products. Not all
products and/or types are available in every country. Please check with an NEC sales representative
for availability and additional information.
• No part of this document may be copied or reproduced in any form or by any means without prior
written consent of NEC. NEC assumes no responsibility for any errors that may appear in this document.
• NEC does not assume any liability for infringement of patents, copyrights or other intellectual property rights of
third parties by or arising from the use of NEC semiconductor products listed in this document or any other
liability arising from the use of such products. No license, express, implied or otherwise, is granted under any
patents, copyrights or other intellectual property rights of NEC or others.
• Descriptions of circuits, software and other related information in this document are provided for illustrative
purposes in semiconductor product operation and application examples. The incorporation of these
circuits, software and information in the design of customer's equipment shall be done under the full
responsibility of customer. NEC assumes no responsibility for any losses incurred by customers or third
parties arising from the use of these circuits, software and information.
• While NEC endeavours to enhance the quality, reliability and safety of NEC semiconductor products, customers
agree and acknowledge that the possibility of defects thereof cannot be eliminated entirely. To minimize
risks of damage to property or injury (including death) to persons arising from defects in NEC
semiconductor products, customers must incorporate sufficient safety measures in their design, such as
redundancy, fire-containment, and anti-failure features.
• NEC semiconductor products are classified into the following three quality grades:
"Standard", "Special" and "Specific". The "Specific" quality grade applies only to semiconductor products
developed based on a customer-designated "quality assurance program" for a specific application. The
recommended applications of a semiconductor product depend on its quality grade, as indicated below.
Customers must check the quality grade of each semiconductor product before using it in a particular
application.
"Standard": Computers, office equipment, communications equipment, test and measurement equipment, audio
and visual equipment, home electronic appliances, machine tools, personal electronic equipment
and industrial robots
"Special": Transportation equipment (automobiles, trains, ships, etc.), traffic control systems, anti-disaster
systems, anti-crime systems, safety equipment and medical equipment (not specifically designed
for life support)
"Specific": Aircraft, aerospace equipment, submersible repeaters, nuclear reactor control systems, life
support systems and medical equipment for life support, etc.
The quality grade of NEC semiconductor products is "Standard" unless otherwise expressly specified in NEC's
data sheets or data books, etc. If customers wish to use NEC semiconductor products in applications not
intended by NEC, they must contact an NEC sales representative in advance to determine NEC's willingness
to support a given application.
(Note)
(1) "NEC" as used in this statement means NEC Corporation and also includes its majority-owned subsidiaries.
(2) "NEC semiconductor products" means any semiconductor product developed or manufactured by or for
NEC (as defined above).
M8E 00. 4
4
User’s Manual U14872EJ1V0UM
Regional Information
Some information contained in this document may vary from country to country. Before using any NEC
product in your application, pIease contact the NEC office in your country to obtain a list of authorized
representatives and distributors. They will verify:
•
Device availability
•
Ordering information
•
Product release schedule
•
Availability of related technical literature
•
Development environment specifications (for example, specifications for third-party tools and
components, host computers, power plugs, AC supply voltages, and so forth)
•
Network requirements
In addition, trademarks, registered trademarks, export restrictions, and other legal issues may also vary
from country to country.
NEC Electronics Inc. (U.S.)
NEC Electronics (Germany) GmbH
NEC Electronics Hong Kong Ltd.
Santa Clara, California
Tel: 408-588-6000
800-366-9782
Fax: 408-588-6130
800-729-9288
Benelux Office
Eindhoven, The Netherlands
Tel: 040-2445845
Fax: 040-2444580
Hong Kong
Tel: 2886-9318
Fax: 2886-9022/9044
NEC Electronics Hong Kong Ltd.
Velizy-Villacoublay, France
Tel: 01-30-67 58 00
Fax: 01-30-67 58 99
Seoul Branch
Seoul, Korea
Tel: 02-528-0303
Fax: 02-528-4411
NEC Electronics (France) S.A.
NEC Electronics Singapore Pte. Ltd.
Madrid Office
Madrid, Spain
Tel: 91-504-2787
Fax: 91-504-2860
United Square, Singapore
Tel: 65-253-8311
Fax: 65-250-3583
NEC Electronics (France) S.A.
NEC Electronics (Germany) GmbH
Duesseldorf, Germany
Tel: 0211-65 03 02
Fax: 0211-65 03 490
NEC Electronics (UK) Ltd.
Milton Keynes, UK
Tel: 01908-691-133
Fax: 01908-670-290
NEC Electronics Taiwan Ltd.
NEC Electronics Italiana s.r.l.
NEC Electronics (Germany) GmbH
Milano, Italy
Tel: 02-66 75 41
Fax: 02-66 75 42 99
Scandinavia Office
Taeby, Sweden
Tel: 08-63 80 820
Fax: 08-63 80 388
Taipei, Taiwan
Tel: 02-2719-2377
Fax: 02-2719-5951
NEC do Brasil S.A.
Electron Devices Division
Guarulhos-SP Brasil
Tel: 55-11-6462-6810
Fax: 55-11-6462-6829
J00.7
User’s Manual U14872EJ1V0UM
5
INTRODUCTION
The CC78K0S C Compiler (hereafter referred to as this C compiler) was developed based on CHAPTER 2
ENVIRONMENT and CHAPTER 3
LANGUAGE in the Draft Proposed American National Standard for
Information Systems — Programming Language C (December 7, 1988).
Therefore, by compiling C source
programs conforming to the ANSI standard with this C compiler, 78K/0S Series application products can be
developed.
The CC78K0S C Compiler Language (this manual) has been prepared to give those who develop software by
using this C compiler a correct understanding of the basic functions and language specifications of this C compiler.
This manual does not cover how to operate this C compiler.
Therefore, after you have comprehended the
contents of this manual, read the CC78K0S C Compiler Operation (U14871E).
For the architecture of 78K/0S Series, refer to the user’s manual of each product of 78K/0S Series.
6
User’s Manual U14872EJ1V0UM
[Target Devices]
Software for the 78K/0S Series microcontrollers can be developed with this C compiler.
Note that an optional device file corresponding to the target device is necessary.
[Readers]
Although this manual is intended for those who have read the user's manual of the microcontroller subject to software
development and have experience in software programming, the readers need not necessarily have a knowledge of
C compilers or C language.
Discussions in this manual assume that the readers are familiar with software
terminology.
[Organization]
This manual consists of the following 13 chapters and appendixes:
CHAPTER 1
GENERAL
Outlines the general functions of C compilers and the performance characteristics and features of
this C compiler.
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
Explains the constituting elements of a C source module file.
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
Explains the data types and storage classes used in C and how to declare the type and storage class
of a data object or function.
CHAPTER 4
TYPE CONVERSIONS
CHAPTER 5
OPERATORS AND EXPRESSIONS
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
CHAPTER 7
STRUCTURES AND UNIONS
Explains the conversions of data types to be automatically carried out by this C compiler.
Describes the operators and expressions that can be used in C and the precedence of operators.
Explains the program control structures of C and the statements to be executed in C.
Explains the concept of structures and unions and how to refer to structure and union members.
CHAPTER 8
EXTERNAL DEFINITIONS
Describes the types of external definitions and how to use external declarations.
CHAPTER 9
PREPROCESSING DIRECTIVES
Details the types of preprocessing directives and how to use each preprocessing directive.
CHAPTER 10 LIBRARY FUNCTIONS
Details the types of C library functions and how to use each library function.
CHAPTER 11 EXTENDED FUNCTIONS
Explains the extended functions of this C compiler that enable users to make the most of the target
device.
CHAPTER 12 REFERENCING BETWEEN ASSEMBLER AND COMPATIBLES
Describes the method of linking a C source program with a program written in Assembly language.
CHAPTER 13 EFFECTIVE UTILIZATION OF COMPILER
Outlines how to effectively use this C compiler.
APPENDIXES A through E
Contains a list of labels for saddr area, a list of segment names, a list of runtime libraries, a list of
library stack consumption, and index for quick reference.
User’s Manual U14872EJ1V0UM
7
[How to Use This Manual]
• For those who are not familiar with C compilers or C language:
Read from CHAPTER 1, as this manual covers from the program control structures of C to the extended functions
of this C compiler. In CHAPTER 1, an example of a C source program is used to show the reference part in this
manual.
• For those who are familiar with C compilers or C language:
The language specifications of this C compiler conform to the ANSI Standard C. Therefore, you may start from
CHAPTER 11, which explains the extended functions unique to this C compiler. When reading CHAPTER 11,
also refer to the user's manual supplied with the target device in the 78K/0S Series if necessary.
[Related Documents]
Document Name
Document No.
CC78K0S C Compiler Operation User’s Manual
U14871E
[Reference]
Draft Proposed American National Standard for Information Systems - Programming Language C (December
7, 1988)
[Terms]
RTOS = 78K/0 Series Real-Time OS RX78K0
[Conventions]
The following symbols and abbreviations are used in this manual:
Symbol
Meaning
⋅⋅⋅
Continuation (repetition) of data in the same format
“
”
Characters enclosed in a pair of double quotes must be input as is.
‘
’
Characters enclosed in a pair of single quotes must be input as is.
…
This part of the program description is omitted.
/
Delimiter
\
Backslash
[
8
]
Parameters in square brackets may be omitted.
User’s Manual U14872EJ1V0UM
CONTENTS
CHAPTER 1
GENERAL...........................................................................................................................21
1.1
C Language and Assembly Language.........................................................................................21
1.2
Program Development Procedure by C Compiler......................................................................23
1.3
Basic Structure of C Source Program .........................................................................................25
1.3.1
Program format.................................................................................................................................25
1.4
Reminders Before Program Development ..................................................................................28
1.5
Features of This C Compiler ........................................................................................................30
(1)
callt/_ _callt functions ..........................................................................................................................30
(2)
Register variables .................................................................................................................................30
(3)
Usage of saddr area.............................................................................................................................30
(4)
sfr area .................................................................................................................................................30
(5)
noauto functions...................................................................................................................................31
(6)
norec/_ _leaf functions.........................................................................................................................31
(7)
bit type variables and boolean/_ _boolean type variables ..................................................................31
(8)
ASM statements....................................................................................................................................31
(9)
Interrupt functions .................................................................................................................................31
(10) Interrupt function qualifier .....................................................................................................................31
(11) Interrupt functions .................................................................................................................................31
(12) CPU control instructions .......................................................................................................................31
(13) Absolute address access function ........................................................................................................31
(14) Bit field declaration ...............................................................................................................................31
(15) Function to change compiler output section name ...............................................................................32
(16) Binary constant description function .....................................................................................................32
(17) Module name change functions ............................................................................................................32
(18) Rotate function......................................................................................................................................32
(19) Multiplication function............................................................................................................................32
(20) Division function....................................................................................................................................32
(21) BCD operation function.........................................................................................................................32
(22) Data insertion function ..........................................................................................................................32
(23) Static model ..........................................................................................................................................32
(24) Type modification..................................................................................................................................32
(25) Pascal function (_ _pascal) ..................................................................................................................32
(26) Automatic pascal functionization of function call interface....................................................................32
(27) Method of int expansion limitation of argument/return value ................................................................33
(28) Array offset calculation simplification method.......................................................................................33
(29) Register direct reference function .........................................................................................................33
(30) Memory manipulation function ..............................................................................................................33
(31) Absolute address allocation specification .............................................................................................33
(32) Static model expansion specification ....................................................................................................33
User’s Manual U14872EJ1V0UM
9
(33) Temporary variables .............................................................................................................................33
(34) Library supporting prologue/epilogue....................................................................................................33
CHAPTER 2
2.1
2.2
2.3
Character Sets .............................................................................................................................. 35
(1)
Character sets.......................................................................................................................................35
(2)
escape sequences ................................................................................................................................36
(3)
Trigraph sequences ..............................................................................................................................36
Keywords....................................................................................................................................... 37
(1)
ANSI-C keywords ..................................................................................................................................37
(2)
Keywords added for the CC78K0S .......................................................................................................37
Identifiers....................................................................................................................................... 38
2.3.1
2.3.2
Scope of identifiers ...........................................................................................................................39
(1)
Function scope ........................................................................................................................39
(2)
File scope ................................................................................................................................39
(3)
Block scope .............................................................................................................................40
(4)
Function prototype scope ........................................................................................................40
Linkage of identifiers.........................................................................................................................40
(1)
External linkage.......................................................................................................................40
(2)
Internal linkage ........................................................................................................................40
(3)
No linkage ...............................................................................................................................40
2.3.3
Name space for identifiers ................................................................................................................41
2.3.4
Storage duration of objects...............................................................................................................41
2.3.5
2.3.6
2.4
CONSTRUCTS OF C LANGUAGE .................................................................................34
(1)
Static storage duration ............................................................................................................41
(2)
Automatic storage duration .....................................................................................................41
Data types.........................................................................................................................................41
(1)
Basic types ..............................................................................................................................42
(2)
Character types .......................................................................................................................46
(3)
Incomplete types .....................................................................................................................46
(4)
Derived types ..........................................................................................................................46
(5)
Scalar types.............................................................................................................................47
Compatible type and composite type................................................................................................48
(1)
Compatible type ......................................................................................................................48
(2)
Composite type .......................................................................................................................48
Constants ...................................................................................................................................... 49
2.4.1
Floating-point constant .....................................................................................................................49
2.4.2
Integer constant ................................................................................................................................49
(1)
10
Decimal constant.....................................................................................................................49
(2)
Octal constant .........................................................................................................................50
(3)
Hexadecimal constant .............................................................................................................50
2.4.3
Enumeration constants .....................................................................................................................50
2.4.4
Character constants..........................................................................................................................51
2.5
String Literal.................................................................................................................................. 51
2.6
Operators....................................................................................................................................... 51
User’s Manual U14872EJ1V0UM
2.7
Delimiters .......................................................................................................................................52
2.8
Header Name..................................................................................................................................52
2.9
Comment ........................................................................................................................................52
CHAPTER 3
3.1
3.2
DECLARATION OF TYPES AND STORAGE CLASSES .............................................53
Storage Class Specifiers ..............................................................................................................54
(1)
typedef ..................................................................................................................................................54
(2)
extern ....................................................................................................................................................54
(3)
static .....................................................................................................................................................54
(4)
auto .......................................................................................................................................................54
(5)
register ..................................................................................................................................................54
Type Specifiers ..............................................................................................................................55
3.2.1
Structure specifier and union specifier .............................................................................................57
(1)
Structure specifier ...................................................................................................................57
(2)
Union specifier ........................................................................................................................57
(3)
Bit field ....................................................................................................................................58
3.2.2
Enumeration specifiers .....................................................................................................................59
3.2.3
Tags..................................................................................................................................................60
3.3
Type Qualifiers...............................................................................................................................61
3.4
Declarators.....................................................................................................................................62
3.4.1
Pointer declarators ...........................................................................................................................62
3.4.2
Array declarators ..............................................................................................................................63
3.4.3
Function declarators (including prototype declarations) ...................................................................63
3.5
Type Names ...................................................................................................................................64
3.6
typedef Declarations .....................................................................................................................65
3.7
Initialization....................................................................................................................................67
(1)
Initialization of objects which have a static storage duration ................................................................67
(2)
Initialization of objects which have an automatic storage duration .......................................................67
(3)
Initialization of character arrays ............................................................................................................67
(4)
Initialization of aggregate or union type objects....................................................................................68
CHAPTER 4
4.1
4.2
TYPE CONVERSIONS ......................................................................................................70
Arithmetic Operands .....................................................................................................................72
(1)
Characters and integers (general integral promotion) ..........................................................................72
(2)
Signed integers and unsigned integers ................................................................................................72
(3)
Usual arithmetic type conversions ........................................................................................................73
Other Operands .............................................................................................................................74
(1)
Left-side values and function locators ..................................................................................................74
(2)
void .......................................................................................................................................................74
(3)
Pointers.................................................................................................................................................74
CHAPTER 5
OPERATORS AND EXPRESSIONS ................................................................................75
User’s Manual U14872EJ1V0UM
11
5.1
Primary Expressions .................................................................................................................... 78
5.2
Postfix Operators.......................................................................................................................... 78
5.3
(1)
Subscript operator.................................................................................................................................79
(2)
Function call ..........................................................................................................................................80
(3)
Structure and union member.................................................................................................................81
(4)
Postfix increment/decrement operators ................................................................................................83
Unary Operators ........................................................................................................................... 84
(1)
Prefix increment/decrement operators ..................................................................................................85
(2)
Address and indirect operators .............................................................................................................86
(3)
Unary arithmetic operators (+ – ~ !) ......................................................................................................87
(4)
sizeof operator ......................................................................................................................................88
5.4
Cast Operator................................................................................................................................ 89
5.5
Arithmetic Operators .................................................................................................................... 90
(1)
Multiplicative operators .........................................................................................................................91
(2)
Additive operators .................................................................................................................................92
5.6
Bitwise Shift Operators ................................................................................................................ 93
5.7
Relational Operators .................................................................................................................... 95
5.8
5.9
(1)
Relational operators ..............................................................................................................................96
(2)
Equality operators .................................................................................................................................98
Bitwise Logical Operators ........................................................................................................... 99
(1)
Bitwise AND operator ..........................................................................................................................100
(2)
Bitwise XOR operator..........................................................................................................................101
(3)
Bitwise inclusive OR operator .............................................................................................................102
Logical Operators ....................................................................................................................... 103
(1)
Logical AND operator..........................................................................................................................104
(2)
Logical OR operator ............................................................................................................................105
5.10 Conditional Operators................................................................................................................ 106
5.11 Assignment Operators ............................................................................................................... 107
(1)
Simple assignment operator ...............................................................................................................108
(2)
Compound assignment operators .......................................................................................................109
5.12 Comma Operator ........................................................................................................................ 110
5.13 Constant Expressions................................................................................................................ 111
(1)
General integral constant expression..................................................................................................111
(2)
Arithmetic constant expression ...........................................................................................................111
(3)
Address constant expression ..............................................................................................................111
CHAPTER 6
6.1
12
CONTROL STRUCTURES OF C LANGUAGE............................................................112
Labeled Statements.................................................................................................................... 114
(1)
case label ............................................................................................................................................115
(2)
default label.........................................................................................................................................117
6.2
Compound Statements (Blocks) ............................................................................................... 118
6.3
Expression Statements and Null Statements .......................................................................... 118
6.4
Selection Statements ................................................................................................................. 119
User’s Manual U14872EJ1V0UM
6.5
6.6
(1)
if and if ... else statements ..................................................................................................................120
(2)
switch statement .................................................................................................................................121
Iteration Statements ....................................................................................................................122
(1)
while statement ...................................................................................................................................123
(2)
do statement .......................................................................................................................................124
(3)
for statement .......................................................................................................................................125
Branch Statements......................................................................................................................126
(1)
goto statement ....................................................................................................................................127
(2)
continue statement .............................................................................................................................128
(3)
break statement ..................................................................................................................................129
(4)
return statement..................................................................................................................................130
CHAPTER 7
7.1
7.2
STRUCTURES AND UNIONS........................................................................................131
Structures.....................................................................................................................................132
(1)
Declaration of structure and structure variable ...................................................................................132
(2)
Structure declaration list .....................................................................................................................132
(3)
Arrays and pointers.............................................................................................................................133
(4)
How to refer to structure members .....................................................................................................133
Unions ..........................................................................................................................................134
(1)
Declaration of union and union variable..............................................................................................134
(2)
Union declaration list ..........................................................................................................................134
(3)
Union arrays and pointers...................................................................................................................135
(4)
How to refer to union members...........................................................................................................135
CHAPTER 8
EXTERNAL DEFINITIONS ..............................................................................................137
8.1
Function Definitions....................................................................................................................138
8.2
External Object Definitions ........................................................................................................140
CHAPTER 9
9.1
9.2
9.3
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES) ....................................141
Conditional Inclusion ..................................................................................................................142
(1)
#if directive..........................................................................................................................................143
(2)
#elif directive .......................................................................................................................................144
(3)
#ifdef directive.....................................................................................................................................145
(4)
#ifndef directive...................................................................................................................................146
(5)
#else directive .....................................................................................................................................147
(6)
#endif directive....................................................................................................................................148
Source File Inclusion ..................................................................................................................149
(1)
#include < > directive .........................................................................................................................150
(2)
#include “ ” directive...........................................................................................................................151
(3)
#include preprocessing token string directive.....................................................................................152
Macro Replacement ....................................................................................................................153
User’s Manual U14872EJ1V0UM
13
9.4
(1)
Actual argument replacement .............................................................................................................153
(2)
# operator............................................................................................................................................153
(3)
## operator..........................................................................................................................................153
(4)
Re-scanning and further replacement.................................................................................................154
(5)
Scope of macro definition....................................................................................................................154
(6)
#define directive ..................................................................................................................................155
(7)
#define ( ) directive.............................................................................................................................156
(8)
#undef directive...................................................................................................................................157
Line Control................................................................................................................................. 158
(1)
To change the line number .................................................................................................................158
(2)
To change the line number and the file name.....................................................................................158
(3)
To change using preprocessor token string ........................................................................................158
9.5
#error Preprocessing Directive ................................................................................................. 159
9.6
#pragma Directive....................................................................................................................... 160
9.7
Null Directive............................................................................................................................... 160
9.8
Predefined Macro Names........................................................................................................... 161
CHAPTER 10
LIBRARY FUNCTIONS..................................................................................................163
10.1 Interface Between Functions..................................................................................................... 164
10.1.1
Arguments ......................................................................................................................................164
10.1.2
Return values..................................................................................................................................165
10.1.3
Saving registers to be used by individual libraries ..........................................................................165
(1)
No -ZR option specified.........................................................................................................166
(2)
-ZR option specified ..............................................................................................................167
10.2 Headers........................................................................................................................................ 171
(1)
ctype.h.................................................................................................................................................172
(2)
setjmp.h...............................................................................................................................................173
(3)
stdarg.h (normal model only) ..............................................................................................................174
(4)
stdio.h..................................................................................................................................................174
(5)
stdlib.h.................................................................................................................................................175
(6)
string.h ................................................................................................................................................177
(7)
error.h..................................................................................................................................................178
(8)
errno.h.................................................................................................................................................178
(9)
limits.h .................................................................................................................................................178
(10) stddef.h ...............................................................................................................................................180
(11) math.h (normal model only) ................................................................................................................181
(12) float.h ..................................................................................................................................................183
(13) assert.h (normal model only)...............................................................................................................185
10.3 Re-entrantability (Normal Model Only) ..................................................................................... 185
14
(1)
Functions that cannot be re-entranced ...............................................................................................185
(2)
Functions that use the area secured in the startup routine .................................................................185
(3)
Functions that deal with floating-point numbers..................................................................................185
User’s Manual U14872EJ1V0UM
10.4 Standard Library Functions........................................................................................................186
10.5 Batch Files for Update of Startup Routine and Library Functions.........................................296
10.5.1
CHAPTER 11
Using batch files .............................................................................................................................297
EXTENDED FUNCTIONS..............................................................................................300
11.1 Macro Names ...............................................................................................................................301
11.2 Keywords .....................................................................................................................................302
(1)
Functions ............................................................................................................................................302
(2)
Variables .............................................................................................................................................303
11.3 Memory.........................................................................................................................................304
(1)
Memory model ....................................................................................................................................304
(2)
Register bank......................................................................................................................................304
(3)
Memory space ....................................................................................................................................304
11.4 #pragma Directive .......................................................................................................................306
11.5 How to Use Extended Functions ...............................................................................................308
(1)
callt functions ......................................................................................................................................309
(2)
Register variables ...............................................................................................................................312
(3)
How to use the saddr area..................................................................................................................316
(4)
How to use the sfr area.......................................................................................................................323
(5)
noauto function ...................................................................................................................................326
(6)
norec function .....................................................................................................................................330
(7)
bit type variables .................................................................................................................................335
(8)
ASM statements..................................................................................................................................339
(9)
Interrupt functions ...............................................................................................................................342
(10) Interrupt function qualifier (_ _interrupt)..............................................................................................349
(11) Interrupt functions ...............................................................................................................................351
(12) CPU control instruction .......................................................................................................................354
(13) Absolute address access function ......................................................................................................356
(14) Bit field declaration .............................................................................................................................360
(15) Changing compiler output section name ............................................................................................368
(16) Binary constant ....................................................................................................................................379
(17) Module name changing function ..........................................................................................................381
(18) Rotate function .....................................................................................................................................382
(19) Multiplication function...........................................................................................................................385
(20) Division function ...................................................................................................................................387
(21) BCD operation function ........................................................................................................................390
(22) Data insertion function .........................................................................................................................394
(23) Static model .........................................................................................................................................396
(24) Type modification .................................................................................................................................400
(25) Pascal function.....................................................................................................................................402
(26) Automatic pascal functionization of function call interface...................................................................405
(27) Method of int expansion limitation of argument/return value................................................................406
User’s Manual U14872EJ1V0UM
15
(28) Array offset calculation simplification method ......................................................................................409
(29) Register direct reference function ........................................................................................................411
(30) Memory manipulation function .............................................................................................................415
(31) Absolute address allocation specification ............................................................................................418
(32) Static model expansion specification ...................................................................................................422
(33) Temporary variables.............................................................................................................................432
(34) Library supporting prologue/epilogue ...................................................................................................435
11.6 Modifications of C Source ......................................................................................................... 444
11.7 Function Call Interface ............................................................................................................... 445
11.7.1
Return value....................................................................................................................................446
11.7.2
Ordinary function call interface .......................................................................................................447
(1)
11.7.3
(2)
Location and order of storing arguments...............................................................................448
(3)
Location and order of storing automatic variables.................................................................449
noauto function call interface (normal model only) .........................................................................454
(1)
11.7.4
11.7.6
CHAPTER 12
Passing arguments................................................................................................................454
(2)
Location and order of storing arguments...............................................................................454
(3)
Location and order of storing automatic variables.................................................................455
norec function call interface (normal model)...................................................................................457
(1)
11.7.5
Passing arguments................................................................................................................447
Passing arguments................................................................................................................457
(2)
Location and order of storing arguments...............................................................................457
(3)
Location and order of storing automatic variables.................................................................458
Static model function call interface .................................................................................................460
(1)
Passing arguments................................................................................................................460
(2)
Location and order of storing arguments...............................................................................460
(3)
Location and order of storing automatic variables.................................................................461
Pascal function call interface ..........................................................................................................465
REFERENCING THE ASSEMBLER.............................................................................469
12.1 Accessing Arguments/Automatic Variables ............................................................................ 470
12.1.1
Normal model .................................................................................................................................470
12.1.2
Static model ....................................................................................................................................473
12.2 Storing Return Values ................................................................................................................ 475
12.3 Calling Assembly Language Routines from C Language....................................................... 476
12.4 Calling C Language Routines from Assembly Language....................................................... 480
(1)
Calling the C language function from an assembly language program...............................................480
(2)
Referencing arguments in a C language function ...............................................................................481
12.5 Referencing Variables Defined in Other Languages............................................................... 482
(1)
Referencing variables defined in the C language ...............................................................................482
(2)
Referencing variables defined in the assembly language from the C language .................................483
12.6 Cautions ...................................................................................................................................... 484
16
(1)
‘_’ (underscore) ...................................................................................................................................484
(2)
Argument positions on the stack .........................................................................................................484
User’s Manual U14872EJ1V0UM
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER................................................................485
13.1 Efficient Coding ...........................................................................................................................485
(1)
Using external variable .......................................................................................................................486
(2)
1-bit data .............................................................................................................................................486
(3)
Function definitions .............................................................................................................................486
(4)
Optimization options ...........................................................................................................................487
(5)
Using extended description.................................................................................................................487
APPENDIX A
LIST OF LABELS FOR SADDR AREA .....................................................................489
A.1 Normal Model...............................................................................................................................489
A.2 Static Model .................................................................................................................................491
APPENDIX B
LIST OF SEGMENT NAMES .......................................................................................492
B.1 List of Segment Names...............................................................................................................493
B.2 Location of Segment ...................................................................................................................493
B.3 Example of C Source...................................................................................................................494
B.4 Example of Output Assembler Module .....................................................................................495
APPENDIX C
LIST OF RUNTIME LIBRARIES ..................................................................................499
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION ............................................................505
APPENDIX E INDEX ...............................................................................................................................514
User’s Manual U14872EJ1V0UM
17
LIST OF FIGURES
Figure No.
Title
Page
1-1 Flow of Compilation ...............................................................................................................................................22
1-2 Program Development Procedure by This C Compiler..........................................................................................24
4-1 Usual Arithmetic Type Conversions.......................................................................................................................73
6-1 Control Flows of Selection Statements ................................................................................................................119
6-2 Control Flows of Iteration Statements..................................................................................................................122
6-3 Control Flows of Branch Statements ...................................................................................................................126
10-1 Stack Area When Function Is Called (No -ZR Specified) ..................................................................................167
10-2 Syntax of Format Commands ............................................................................................................................198
10-3 Syntax of Input Format Commands ...................................................................................................................202
11-1 Bit Allocation by Bit Field Declaration (Example 1)............................................................................................362
11-2 Bit Allocation by Bit Field Declaration (Example 2)............................................................................................363
11-3 Bit Allocation by Bit Field Declaration (Example 3)............................................................................................365
12-1 Stack Area After a Call ......................................................................................................................................476
12-2 Stack Area After Returning ................................................................................................................................479
12-3 Placing Arguments on Stack..............................................................................................................................480
12-4 Passing Arguments to C Language ...................................................................................................................481
12-5 Stack Positions of Arguments............................................................................................................................484
18
User’s Manual U14872EJ1V0UM
LIST OF TABLES (1/2)
Table No.
Title
Page
1-1 Maximum Performance Characteristics of This C Compiler ..................................................................................28
2-1 List of Escape Sequences .....................................................................................................................................36
2-2 List of Trigraph Sequence......................................................................................................................................36
2-3 List of Basic Data Types ........................................................................................................................................44
2-4 Exponent Relationships .........................................................................................................................................45
2-5 List of Operation Exceptions ..................................................................................................................................46
4-1 List of Conversions Between Types.......................................................................................................................71
4-2 Conversions from Signed Integral Type to Unsigned Integral Type.......................................................................72
5-1 Evaluation Precedence of Operators .....................................................................................................................77
5-2 Signs of Division/Remainder Operation Result......................................................................................................90
5-3 Shift Operations .....................................................................................................................................................93
5-4 Bitwise AND Operator ..........................................................................................................................................100
5-5 Bitwise XOR Operator..........................................................................................................................................101
5-6 Bitwise OR Operator ............................................................................................................................................102
5-7 Logical AND Operator..........................................................................................................................................104
5-8 Logical OR Operator ............................................................................................................................................105
10-1 List of Passing First Argument (Normal Model) .................................................................................................164
10-2 List of Passing Arguments (Static Model) ..........................................................................................................165
10-3 List of Storing Return Value ...............................................................................................................................165
10-4 Contents of ctype.h ............................................................................................................................................172
10-5 Contents of setjmp.h ..........................................................................................................................................173
10-6 Contents of stdarg.h...........................................................................................................................................174
10-7 Contents of stdio.h .............................................................................................................................................174
10-8 Contents of stdlib.h ............................................................................................................................................175
10-9 Contents of string.h............................................................................................................................................177
10-10 Contents of math.h...........................................................................................................................................181
10-11 Contents of assert.h.........................................................................................................................................185
10-12 Batch Files for Updating Library Functions ......................................................................................................296
User’s Manual U14872EJ1V0UM
19
LIST OF TABLES (2/2)
Table No.
Title
Page
11-1 List of Added Keywords .....................................................................................................................................302
11-2 Utilization of Memory Space ..............................................................................................................................305
11-3 List of #pragma Directives .................................................................................................................................307
11-4 The Number of callt Attribute Functions That Can Be Used When the -QL Option Is Specified .......................310
11-5 Restrictions on callt Function Usage .................................................................................................................310
11-6 Restrictions on Register Variable Usage ...........................................................................................................313
11-7 Restrictions on sreg Variable Usage .................................................................................................................317
11-8 Variables Allocated to saddr Area by -RD Option..............................................................................................319
11-9 Variables Allocated to saddr Area by -RS Option ..............................................................................................320
11-10 Variables Allocated to saddr Area by -RK Option ............................................................................................321
11-11 Operators Using Only Constants 0 or 1 (with Bit Type Variable) .....................................................................336
11-12 Save/Restore Area When Interrupt Function Is Used......................................................................................343
11-13 Details of Type Modification (Change from int and short Type to char Type) ..................................................400
11-14 Details of Type Modification (Change from long Type to int Type) ..................................................................401
11-15 Interrupt Functions Targeted for Saving ..........................................................................................................422
11-16 Location of Storing Return Value.....................................................................................................................446
11-17 Location Where First Argument Is Passed (on Function Call Side) ................................................................447
11-18 Areas to Which Arguments Are Passed in Static Model..................................................................................460
12-1 Passing Arguments (Function Call Side) ...........................................................................................................470
12-2 Storing of Arguments/Automatic Variables (Inside Called Function) .................................................................471
12-3 Passing Arguments (Function Call Side) ...........................................................................................................473
12-4 Storing of Arguments/Automatic Variables (Inside Called Function) .................................................................473
12-5 Storage Location of Return Values ....................................................................................................................475
C-1 List of Runtime Libraries .....................................................................................................................................499
D-1 List of Standard Library Stack Consumption .......................................................................................................508
D-2 List of Runtime Library Stack Consumption ........................................................................................................513
20
User’s Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
The CC78K0S Series C Compiler is a language processing program which converts a source program written in
the C language for the 78K/0S Series or ANSI-C into machine language. Object files or assembler source files for
the 78K/0S Series can be obtained by using this CC78K0S Series C compiler.
1.1
C Language and Assembly Language
To have a microcontroller do its job, programs and data are necessary. These programs and data must be written
by a human being (programmer) and stored in the memory section of the microcontroller. Programs and data that
can be handled by the microcontroller are nothing but a set or combination of binary numbers called machine
language.
An assembly language is a symbolic language characterized by one-to-one correspondence of its symbolic
(mnemonic) statements with machine language instructions.
Because of this one-to-one correspondence, the
assembly language can provide the computer with detailed instructions (for example, to improve I/O processing
speed). However, this means that the programmer must instruct each and every operation of the computer. For this
reason, it is difficult to understand the logic structure of the program at glance and the programmer is likely to make
errors in coding.
High-level languages were developed as substitutes for such assembly languages. The high-level languages
include a language called C, which allows the programmer to write a program without regard to the architecture of the
computer.
As compared with assembly language programs, it can be said that programs written in C have an easy-tounderstand logic structure.
C has a rich set of parts called functions for use in creating programs. In other words, the programmer can write a
program by combining these functions.
C is characterized by its ease of understanding by human beings. However, understanding of languages by the
microcontroller cannot be extended up to a program written in C. Therefore, to have the computer understand the C
language program, another program is required to translate C language statements into the corresponding machine
language instructions. A program that translates the C language into machine language is called a C compiler.
This C compiler accepts C source modules as inputs and generates object modules or assembler source modules
as outputs. Therefore, the programmer can write a program in C and if he or she wishes to instruct the computer up
to details of program execution, the C source program can be modified in assembly language. The flow of translation
by this C compiler is illustrated in Figure 1-1.
User’s Manual U14872EJ1V0UM
21
CHAPTER 1
GENERAL
Figure 1-1. Flow of Compilation
Program written
in C language
Program coded in a set
of binary numbers
Translating program
(Compiler)
(C source module file)
(Object module file)
(Assembler source
module file)
Program coded in a set
of binary numbers
Translating program
(Assembler)
(Object module file)
22
User’s Manual U14872EJ1V0UM
CHAPTER 1
1.2
GENERAL
Program Development Procedure by C Compiler
Product (program) development by the C compiler requires a linker to unite object module files created by the
compiler, a librarian to create library files, and a debugger to locate and correct bugs (errors or mistakes) in each
created C source program.
The software required in connection with this C compiler is shown below.
• Editor .......................................... for source module file creation
• RA78K0S assembler package
Assembler................................... for converting assembly language into machine language
Linker .......................................... for linking object module files
for determining location address of relocatable segment
Object converter ......................... for conversion to HEX-format object module file
Librarian...................................... for creating library files
• Debugger (for 78K/0S)................ for debugging C source module files
The product development procedure by the C compiler is as shown below.
<1> Divides the product into functions.
<2> Creates a C source module for each function.
<3> Translates each C source module.
<4> Registers the modules to be used frequently in the library.
<5> Links object module files.
<6> Debugs each module.
<7> Converts object modules into HEX-format object files.
As mentioned earlier, this C compiler translates (compiles) a C source module file and creates an object module
file or assembler source module file.
By manually optimizing the created assembler source module file and
embedding it into the C source, efficient object modules can be created. This is useful when high-speed processing
is a must or when modules must be made compact.
User’s Manual U14872EJ1V0UM
23
CHAPTER 1
GENERAL
Figure 1-2. Program Development Procedure by This C Compiler
C source
Structured
assembler source
Include file
Structured assembler
C compiler
Assembler
source
Assembler
source
Assembler
MX78K0S
Object module file
Library file
Librarian
Assemble list
Library
file
Linker
Load module file
Object converter
Integrated debugger
Dedicated parallel
interface
T
LA
O
R
Hex-format
object
IR
C
U
IT
E
M
Absolute
assemble list
System
simulator
U
List converter
IN
C
In-circuit emulator
POWER
RS-232C
PROM programmer
24
User’s Manual U14872EJ1V0UM
CHAPTER 1
1.3
GENERAL
Basic Structure of C Source Program
1.3.1 Program format
A C language program is a collection of functions.
These functions must be created so that they have
independent special-purpose or characteristic actions. All C language programs must have a function main which
becomes the main routine in C and is the first function that is called when execution begins.
Each function consists of a header part, which defines its function name and arguments, and a body part, which
consists of declarations and statements. The format of C programs is shown below.
Definition of variables/constants
Definition of each data, variable, and macro instruction
main (arguments)
Header of the function main
{
statement1;
statement2;
function1 (arguments);
Body of the function main
function2 (arguments);
}
function1 (arguments)
{
statement1;
Function 1
statement2;
}
function2 (arguments)
{
statement1;
Function 2
statement2;
}
User’s Manual U14872EJ1V0UM
25
CHAPTER 1
GENERAL
An actual C source program looks like this.
#define TRUE
1
#define FALSE
0
#define SIZE
200
#define xxx xxx ....... Preprocessor directive (macro definition)
<6>
xxx xxxx (xxx, xxx)...................... Function prototype declarator
<7>
char mark[SIZE+1];
char xxx .............. Type declarator
External definition
<5>
main()
xx [xx]..........................................................................Operator
<2>
int i,prime,k,count;
int xxx .............................................................. Type declarator
<1>
count=0;
xx = xx.........................................................................Operator
<2>
for(i=0;i<=SIZE;i++)
for (xx;xx;xx) xxx ;........................................... Control structure
<3>
prime=i+i+3;
xxx = xxx + xxx + xxx................................................Operator
<2>
printf("%6d",prime);
xxx (xxx) ; .................................................................Operator
<2>
if (xxx) xxx ; ....................... Control structure
<3>
xxx (xxx) ;........................................Operator
<2>
void printf(char *,int);
void putchar(char);
<1>
{
mark[i]=TRUE;
for(i=0;i<=SIZE;i++){
if(mark[i]){
count++;
if((count%8)==0) putchar('\n');
for(k=i+prime;k<=SIZE;k+=prime)
mark[k]=FALSE;
}
}
printf("\n%d primes found.",count);
}
void printf(char *s,int i)
{
int j;
char *ss;
j=i;
ss=s;
}
void putchar(char c)
{
char d;
d=c;
}
26
User’s Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
<1> Declaration of type and storage class
The data type and storage class of an identifier that indicates a data object are declared. For details, see
CHAPTER 3 DECLARATION OF TYPES AND STORAGE CLASSES.
<2> Operator and expression
These are the statements that instruct the compiler to perform operations such as arithmetic operations,
logical operations, or assignments. For details, see CHAPTER 5 OPERATORS AND EXPRESSIONS.
<3> Control structure
This is a statement that specifies the program flow. C has several instructions for each of control structures
such as conditional control, iteration, and branch. For details, see CHAPTER 6 CONTROL STRUCTURES
OF C LANGUAGE.
<4> Structure or union
A structure or union is declared. A structure is a data object that contains several subobjects or members
that may have different types. A union is defined when two or more variables share the same memory. For
details, see CHAPTER 7 STRUCTURES AND UNIONS.
<5> External definition
A function or external object is declared. A function is one element when a C language program is divided
by a special-purpose or characteristic action. A C program is a collection of these functions. For details, see
CHAPTER 8 EXTERNAL DEFINITIONS.
<6> Preprocessing directive
This is an instruction for the compiler. #define instructs the compiler to replace a parameter which is the
same as the first operand with the second operand if the parameter appears in the program. For details, see
CHAPTER 9 PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES).
<7> Declaration of function prototype
The return value and argument type of a function are declared.
User’s Manual U14872EJ1V0UM
27
CHAPTER 1
1.4
GENERAL
Reminders Before Program Development
Before starting development of a program, keep in mind the points (limit values or minimum guaranteed values)
summarized in Table 1-1 below.
Table 1-1. Maximum Performance Characteristics of This C Compiler (1/2)
No.
Item
Limit Value/Min.
Guaranteed Value
1
Nesting level of compound statements, looping statements, or
conditional control statements
45 levels
2
Nesting of conditional translations
255 levels
3
Number of arithmetic type, structure type, pointer to qualify union type
or incomplete type, array, and function declarator in a declaration (or
any combination of these).
12 levels
4
Nesting of parentheses per expression
32 levels
5
Number of characters which have a meaning as a macro name
256 characters
6
Number of characters which have a meaning as an internal or external
symbol name
249 characters
7
Number of symbols per source module file
1,024 symbolsNote 1
8
Number of symbols which has block scope within a block
255 symbolsNote 1
9
Number of macros per source module file
10,000 macrosNote 2
10
Number of parameters per function definition or function call
39 parameters
11
Number of parameters per macro definition or macro call
31 parameters
12
Number of characters per logical source line
2048 characters
13
Number of characters within a string literal after linkage
509 characters
14
Size of one data object
65,535 bytes
15
Nesting of #include directives
8 levels
16
Number of case labels per switch statement
257 labels
17
Number of source lines per translation unit
Approx. 30,000 lines
18
Number of source lines that can be translated without temporary file
creation
Approx. 300 lines
19
Nest of function calls
40 levels
20
Number of labels within a function
33 labels
Notes 1. This value applies when symbols can be processed with the available memory space alone without using
any temporary files. When a temporary file is used because of insufficient memory space, this value must
be changed according to the file size.
2. This value includes the reserved macro definitions of the C compiler.
28
User’s Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
Table 1-1. Maximum Performance Characteristics of This C Compiler (2/2)
No.
Limit Value/Min.
Guaranteed Value
Item
21
Total size of code, data, and stack segments per object module
65,535 bytes
22
Number of members per structure or union
256 members
23
Number of enum constants per enumeration
255 constants
24
Nest of structures or unions inside a structure or union
15 levels
25
Nest of initializer elements
15 levels
26
Number of function definitions in 1 source module file
1,000
27
Level of the nest of declarator enclosed with parentheses inside a
complete declarator.
591
28
Nest of macros
200
29
Number of -I include file path specifications
64
User’s Manual U14872EJ1V0UM
29
CHAPTER 1
1.5
GENERAL
Features of This C Compiler
This C compiler has extended functions for CPU code generation that is not supported by the ANSI (American
National Standards Institute) Standard C.
The extended functions of the C compiler allow the special function
registers for the 78K/0S Series to be described at the C language level and thus help shorten object code and
improve program execution speed.
For details of these extended functions, see CHAPTER 11
EXTENDED
FUNCTIONS in this manual.
Outlined here are the extended functions used to help shorten object code and improve execution speed.
• Functions can be called using the callt table area. ..........................................
callt /_ _callt functions
• Variables can be allocated to registers. ............................................................
Register variables
• Variables can be allocated to the saddr area...................................................
sreg/_ _sreg
• sfr names can be used. ....................................................................................
sfr area
• Functions that do not output code for stack frame formation can be created. ..
noauto functions,
norec/_ _leaf functions
• An assembly language program can be described in a C source program ..... .
ASM statements
• Accessing the saddr or sfr area can be made on a bit-by-bit basis.................
bit type variables,
boolean/_ _boolean type
variables
• A bit field can be specified with unsigned char type........................................
Bit field declaration
• The code to multiply can be directly output with inline expansion.....................
Multiplication function
• The code to divide can be directly output with inline expansion. ......................
Division function
• The code to rotate can be directly output with inline expansion........................
Rotate function
• Specific addresses in the memory space can be accessed. ............................
Absolute address function
• Specific data and instructions can be directly embedded in the code area. .....
Data insertion function
• The used stack is corrected on the called function side. ..................................
_ _pascal function
An outline of the expansion functions of this compiler is shown below. For details of each expansion function, refer
to CHAPTER 11.
(1) callt/_ _callt functions
Functions can be called by using the callt table area. The address of each function to be called (this function is
called a callt function) is stored in the callt table from which it can be called later. This makes the object code
shorter than for the ordinary call instruction call.
(2) Register variables
Variables declared with the register storage class specifier are allocated to the register or saddr area.
Instructions to the variables allocated to the register or saddr area are shorter in code length than those to
memory. This helps shorten object and improves program execution speed as well.
(3) Usage of saddr area
Variables declared with the keyword sreg can be allocated to the saddr area.
Instructions to these sreg
variables are shorter in code length than those to memory. This helps shorten object code and also improves
program execution speed. Variables can be allocated to the saddr area also by option.
(4) sfr area
By declaring use of sfr names, manipulations on the sfr area can be described in the C source file.
30
User’s Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
(5) noauto functions
Functions declared as noauto do not output code for preprocessing and postprocessing (stack frame formation).
By calling a noauto function, arguments are passed via registers. This helps shorten object code and improve
program execution speed as well. This function has restrictions with argument/automatic variables. For the
details, refer to Section 11.5 (5) noauto function.
(6) norec/_ _leaf functions
Functions declared as norec/_ _leaf do not output code for preprocessing and postprocessing (stack frame
formation). By calling a norec/_ _leaf function, arguments are passed via registers as much as possible.
Automatic variables to be used inside a norec/_ _leaf function are allocated to registers or the saddr area. This
helps shorten object code and also improve program execution speed. This function has restrictions with
argument/automatic variables and is not allowed to call a function. For the details, refer to Section 11.5 (6)
norec function.
(7) bit type variables and boolean/_ _boolean type variables
Variables having a 1-bit storage area are generated. By using the bit type variable or boolean/_ _boolean type
variable, the saddr area can be accessed in bit units.
The boolean/_ _boolean type variable is the same as the bit type variable in terms of both function and usage.
(8) ASM statements
The assembler source program described by the user can be embedded in an assembler source file to be output
by this C compiler.
(9) Interrupt functions
The preprocessing directive outputs a vector table and outputs an object code corresponding to the interrupt.
This directive allows programming of interrupt functions at the C source level.
(10) Interrupt function qualifier
This qualifier allows the setting of a vector table and interrupt function definitions to be described in a separate
file.
(11) Interrupt functions
An interrupt disable instruction and an interrupt enable instruction are embedded in objects.
(12) CPU control instructions
Each of the following instructions is embedded in objects:
Instruction to set the value for halt to the STBC register
Instruction to set the value for stop to the STBC register
nop instruction
(13) Absolute address access function
Codes that access the ordinary memory space are created through direct inline expansion without resort to a
function call, and an object file is created.
(14) Bit field declaration
By specifying a bit field to be unsigned char type, the memory can be saved, object code can be shortened, and
execution speed can be improved.
User’s Manual U14872EJ1V0UM
31
CHAPTER 1
GENERAL
(15) Function to change compiler output section name
By changing the compiler section output name, the section can be independently allocated with a linker.
(16) Binary constant description function
Binary can be described in the C source.
(17) Module name change functions
Object module names can be freely changed in the C source.
(18) Rotate function
The code to rotate the value of an expression to the object can be directly output with inline expansion.
(19) Multiplication function
The code to multiply the value of an expression to the object can be directly output with inline expansion. This
function can shorten the object code and improve the execution speed.
(20) Division function
The code to divide the value of an expression to the object can be directly output with inline expansion. This
function can shorten the object code and improve the execution speed.
(21) BCD operation function
This function uses direct inline expansion to output the code that performs a BCD operation on the operation
value in an object. A BCD operation is an operation for converting each digit of a decimal number into binary
and storing it in 4 bits.
(22) Data insertion function
Constant data is inserted in the current address. Specific data and instructions can be embedded in the code
area without using assembler description.
(23) Static model
Specifying the -SM option during compilation enables the shortening of object codes, improvement of execution
speed, realization of high-speed interrupt processing, and saving of memory space.
(24) Type modification
By specifying the -ZI option and -ZL option, int/short types are regarded as char type, and long type is
regarded as int type.
(25) Pascal function (_ _pascal)
The stack correction used for placing arguments during the function call is performed on the function callee, not
on the function caller. This shortens the object code when a lot of function call appears.
(26) Automatic pascal functionization of function call interface
By specifying the -ZR option during compilation, the _ _pascal attribute is added to functions other than the
norec/_ _interrupt/variable length argument functions.
32
User’s Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
(27) Method of int expansion limitation of argument/return value
By specifying the -ZB option during compilation, the object code can be shortened and execution speed can be
improved.
(28) Array offset calculation simplification method
By specifying the -QW2, -QW3, -QW4, and -QW5 options during compilation, the offset calculation code is
simplified, the object code is shortened, and the execution speed is improved.
(29) Register direct reference function
Register access can be made easily by the C specification by coding this function in the source in the same
format as the function call or by declaring the use of this register direct reference function by the #pragma
realregister directive in the module.
(30) Memory manipulation function
By the #pragma inline directive, an object file is generated by the output of the standard library functions
memcpy and memset with direct inline expansion instead of function call.
This function can improve the
execution speed.
(31) Absolute address allocation specification
By declaring _ _directmap in the module in which the variable to be allocated to an absolute address is to be
defined, one or more variables can be allocated to the same arbitrary address.
(32) Static model expansion specification
By specifying the -ZM option during compilation, restrictions on existing static models can be relaxed, improving
descriptiveness.
(33) Temporary variables
By specifying the -SM and -ZM options during compilation and declaring _ _temp for arguments and automatic
variables, an area for arguments and automatic variables can be reserved.
In addition, if the sections containing arguments and those containing automatic variables are clearly identified
and the _ _temp declaration is applied to variables that do not require a guaranteed value match before and
after a function call, memory can be reserved.
(34) Library supporting prologue/epilogue
By specifying the -ZD option during compilation, the prologue/epilogue code can be replaced by a library,
shortening the object code.
User’s Manual U14872EJ1V0UM
33
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
This chapter explains the constituting elements of a C source module file.
A C source module file consists of the following tokens (distinguishable units in a sequence of characters).
Keywords
Identifiers
Constants
String literal
Operators
Delimiters
Header name
No. of preprocesses
Comment
The tokens used in the C program description example are shown below.
#include “expand.h”
extern............................................................
Keyword
extern bit data2;
data1, data2..................................................
Identifiers
void main()
void ...............................................................
Keyword
data1=1;
1....................................................................
Constant
data2=0;
0....................................................................
Constant
while(data1){
extern void testb(void);
extern void chgb(void);
extern bit data1;
{
while..............................................................
Keyword
data1=data2;
{ } .................................................................
Delimiter
testb();
=....................................................................
Operator
}
if....................................................................
Keyword
&& .................................................................
Operator
( ) .................................................................
Operator
void lprintf(char *s,int i)
lprintf.............................................................
Identifier
{
if(data1&&data2){
chgb();
}
}
char, int.........................................................
Keywords
int j;
s, i .................................................................
Identifiers
char *ss;
* ....................................................................
Operator
j=i;
ss=s;
}
.
.
.
34
User’s Manual U14872EJ1V0UM
CHAPTER 2
2.1
CONSTRUCTS OF C LANGUAGE
Character Sets
(1) Character sets
Character sets to be used in C programs include a source character set to be used to describe a source file and
an execution character set to be interpreted in the execution environment.
The value of each character in the execution character set is represented by JIS code.
The following characters can be used in the source character set and execution character set:
26 uppercase letters
A B C D E
F
G
H
I
J
K
L
M
R
S
T
U
V
W
X
Y
Z
26 lowercase letters
a b c d e
f
g
h
i
j
k
l
m
r
s
t
u
v
w
x
y
z
10 decimal numbers
0 1 2 3 4
5
6
7
8
9
29 graphic characters
! “ # % &
‘
(
)
*
+
,
-
.
/
[
\
]
^
—
{
|
}
~
N
n
;
O
o
<
P
p
=
Q
q
>
?
:
and nonprintable control characters which indicate Space, Horizontal Tab, Vertical Tab, Form Feed, etc. (see
escape sequences below.)
Remark
In character constants, string literal, and comment statements, characters other than above may also be
used.
User’s Manual U14872EJ1V0UM
35
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(2) Escape sequences
Nongraphic characters used for control characters as for alert, formfeed, and such are represented by escape
sequences. Each escape sequence consists of the \ sign and an alphabetic character.
Nongraphic characters represented by escape sequences are shown below.
Table 2-1. List of Escape Sequences
Escape Sequence
Meaning
Character Code
\a
Alert
07H
\b
Backspace
08H
\f
Formfeed
0CH
\n
New Line
0AH
\r
Carriage Return
0DH
\t
Horizontal Tab
09H
\v
Vertical Tab
0BH
(3) Trigraph sequences
When a source file includes a list of the three characters (called “trigraph sequence”) shown in the left column of
the table below, the list of the three characters is converted into the corresponding single character shown in the
right column.
Table 2-2. List of Trigraph Sequence
36
Trigraph Sequence
Meaning
??=
#
??(
[
??/
\
??)
]
??’
^
??<
{
??!
|
??>
}
??-
~
User’s Manual U14872EJ1V0UM
CHAPTER 2
2.2
CONSTRUCTS OF C LANGUAGE
Keywords
(1) ANSI-C keywords
The following tokens are used by the C compiler as keywords and thus cannot be used as labels or variable
names.
auto
break
case
char
const
continue
default
do
double
else
enum
extern
for
float
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
(2) Keywords added for the CC78K0S
In this C compiler the following tokens have been added as keywords to implement its expanded functions.
These tokens cannot be used as labels or variable names nor can ANSI (when an uppercase character is
included, the token is not regarded as a keyword).
Keywords which do not start with “_ _” can be made invalid by specifying the option (-ZA) that enables only
ANSI-C language specification.
callf, _ _callf, _ _banked 1 to 15, _ _rtos_interrupt, and _ _interrupt_brk are taken as keywords for compatibility
with the CC78K0.
_ _callt/callt .................................
Declaration of callt function
_ _callf/callf .................................
Declaration of callf function
_ _sreg/sreg......................................
Declaration of sreg variable
noauto ..................................................
Declaration of noauto function
_ _leaf/norec ...................................
Declaration of norec function
bit.........................................................
Declaration of bit type variable
_ _boolean/boolean.........................
Declaration of boolean type variable
_ _interrupt......................................
Hardware interrupt function
_ _interrupt_brk .............................
Software interrupt function
_ _banked 1 to 15...........................
Bank function
_ _asm ..................................................
asm statement
_ _rtos_interrupt...........................
Interrupt handler for RTOS
_ _pascal ............................................
Pascal function
_ _directmap......................................
Absolute address allocation specification
_ _temp ................................................
Temporary variable
_ _mxcall ............................................
_ _mxcall function
Note
Note Reserved keyword for interface with MX. This keyword must not be used by users.
User’s Manual U14872EJ1V0UM
37
CHAPTER 2
2.3
CONSTRUCTS OF C LANGUAGE
Identifiers
An identifier is the name given to a variable such as:
Function
Object
Tag of structure, union, or enumeration type
Member of structure, union, or enumeration type
typedef name
Label name
Macro name
Macro parameter
Each identifier can consist of uppercase letters, lowercase letters, numeric characters, and the underscores. The
following characters can be used as identifiers.
There is no restriction for the maximum length of the identifier. In this compiler, however, only the first 249
characters can be identified (refer to Table 1-1 Maximum Performance Characteristics of this C Compiler).
_(underscore)
a
b
c
d
e
f
g
h
i
n
o
p
q
r
s
t
u
v
w
x
y
z
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
0
1
2
3
4
5
6
7
8
9
j
k
l
m
All identifiers must begin with other than a numerical character (namely, a letter or an underscore) and must not be
the same as any keyword.
38
User’s Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.3.1 Scope of identifiers
The range within which the use of an identifier becomes effective is determined by the location at which the
identifier is declared. The scope of identifiers is divided into the following four types.
• Function scope
• File scope
• Block scope
• Function prototype scope
extern __boolean data1, data2;
data1, data2 .................................................... File scope
void testb (int x);
x............................................... Function prototype scope
void main(void)
{
cot................................................................. Block scope
int cot;
data1=1;
data2=0;
while(data1){
data1=data2;
j1:
j1.............................................................
Function scope
testb(cot);
}
}
void testb(int x)
x.................................................................... Block scope
{
.
.
.
(1) Function scope
Function scope refers to the entirety within a function. An identifier with function scope can be referenced from
anywhere within a specified function.
Identifiers that have function scope are label names only.
(2) File scope
File scope refers to the entirety of a translation (compiling) unit. Identifiers that are declared outside a block or
parameter list all have file scope. An identifier that has file scope can be referenced from anywhere within the
program.
User’s Manual U14872EJ1V0UM
39
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(3) Block scope
Block scope refers to the range of a block (a sequence of declarations and statements enclosed by a pair of
curly braces { } which begins with the opening brace and ends with the closing brace.
Identifiers that are declared inside a block or parameter list all have block scope. An identifier that has block
scope is valid until the innermost brace pair including the declaration of the identifier is closed.
(4) Function prototype scope
Function prototype scope refers to the range of a declared function from its beginning to the end. Identifiers that
are declared inside a parameter list within a function prototype all have function prototype scope. An identifier
that has function prototype scope is valid within a specified function.
2.3.2 Linkage of identifiers
The linkage of identifiers refers to the situation whereby the same identifier declared more than once in different
scopes or in the same scope can be referenced as the same object or function. By being linked, identifiers are
regarded to be one and the same. Identifiers may be linked in the following three different ways: external linkage,
internal linkage and no linkage
(1) External linkage
External linkage refers to identifiers to be linked in translation (compiling) units that constitute the entire program
and as a collection of libraries.
The following identifiers have external linkage examples:
• The identifier of a function declared without storage class specification
• The identifier of an object or function declared as extern, which has no storage class specification
• The identifier of an object which has file scope but has no storage class specification.
(2) Internal linkage
Internal linkage refers to identifiers to be linked within one translation (compiling) unit.
The following identifier has an internal linkage example:
• The identifier of an object or function which has file scope and contains the storage class specifier static.
(3) No linkage
An identifier that has no linkage to any other identifier is an inherent entity.
Examples of identifiers that have no linkage are as follows:
• An identifier which does not refer to a data object or function
• An identifier declared as a function parameter
• The identifier of an object which does not have storage class specifier extern inside a block
40
User’s Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.3.3 Name space for identifiers
All identifiers are classified into the following “name spaces”.
• Label name ........................................................ Distinguished by a label declaration.
• Tag name of structure, union, or enumeration... Distinguished by the keyword struct, union or enum
• Member name of structure or union................... Distinguished by the dot (.) operator or arrow (->) operator.
• Ordinary identifiers (other than above) .............. Declared as ordinary declarators or enumeration type constants.
2.3.4 Storage duration of objects
Each object has a storage duration that determines its lifetime (how long it can remain in memory). This storage
duration is divided into the following two categories: static storage duration and automatic storage duration
(1) Static storage duration
Before executing an object program that has a static duration, an area is reserved for objects and values to be
stored are initialized once. The objects exist throughout the execution of the entire program and retain the
values last stored.
Objects that have a static storage duration are as follows.
• Objects that have external linkage
• Objects that have internal linkage
• Objects declared by storage class specifier static
(2) Automatic storage duration
For objects that have automatic storage duration, an area is reserved when they enter a block to be declared.
If initialization is specified, the objects are initialized as they enter from the beginning of the block. In this case, if
any object enters the block by jumping to a label within the block, the object will not be initialized.
For objects that have automatic storage duration, the reserved area will not be guaranteed after the execution of
the declared block.
Objects that have automatic storage duration are as follows.
• Objects that have no linkage
• Objects declared inside a block without storage class specifier static
2.3.5 Data types
Data types determine the meaning of a value to be stored in each object and are divided into the following three
categories.
• Object type................................................... Type that indicates an object with size information
• Function type ............................................... Type that indicates a function
• Incomplete type ........................................... Type that indicates an object without size information
The type categories are shown below.
User’s Manual U14872EJ1V0UM
41
CHAPTER 2
•
Basic types
CONSTRUCTS OF C LANGUAGE
Integral types
(Arithmetic types)
char type
Signed
signed char
integral
short int
types
int
long int
Unsigned integral types
(specified by unsigned)
Enumeration type
Floating-point types
float
double
long double
•
Character types
char
signed char
unsigned char
•
Incomplete types
Array with an indefinite object size, structure, union, and void type
•
Derived types
Array type
Structure type
Aggregate type
Union type
Function type
Pointer type
•
Scalar types
Basic (Arithmetic types)
Pointer type
(1) Basic types
Basic data types are also referred to as “arithmetic types”. The arithmetic types consist of integral types and
floating-point types.
(a) Integral types
Integral data types are subdivided into four types. Each of these types has a value represented by the
binary numbers 0 and 1.
• char type
• Signed integral type
• Unsigned integral type
• Enumeration type
(i)
char type
The char type has a sufficient size to store any character in the basic execution character set. The
value of a character to be stored in a char type object becomes positive. Data other than characters is
handled as an unsigned integer. In this case, however, if an overflow occurs, the overflowed part will
be ignored.
42
User’s Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(ii) Signed integral type
The signed integral type is subdivided into the following four types:
• signed char
• short int
• int
• long int
An object declared with the signed char type has an area of the same size as the char type without a
qualifier.
An int object without a qualifier has a size natural to the CPU architecture of the execution
environment. A signed integral type data has its corresponding unsigned integral type data. Both
share an area of the same size. The positive number of a signed integral type data is a subset of
unsigned integral type data.
(iii) Unsigned integral type
The unsigned integral type is data defined with the unsigned keyword. No overflow occurs in any
computation involving unsigned integral type data. The reason is that if the result of a computation
involving unsigned integral type data becomes a value which cannot be represented by an integral
type, the value will be divided by the maximum number which can be represented by an unsigned
integral type plus 1 and substituted with the remainder in the result of the division.
(iv) Enumeration type
Enumeration is a collection or list of named integer constants. An enumeration type consists of one or
more sets of enumeration.
(b) Floating-point types
The floating-point types are subdivided into the three types.
• float
• double
• long double
In this compiler, double and long double types as well as float type are supported as a floating-point
expression for the single-precision normalized number that is specified in ANSI/IEEE 754-1985. Thus,
float, double, and long double types have the same value range.
User’s Manual U14872EJ1V0UM
43
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
Table 2-3. List of Basic Data Types
Type
Value Range
(signed) char
–128 to +127
unsigned char
0 to 255
(signed) short int
–32768 to +32767
unsigned short int
0 to 65535
(signed) int
–32768 to +32767
unsigned int
0 to 65535
(signed) long int
–2147483648 to +2147483647
unsigned long int
0 to 4294967295
float
1.17549435E–38F to 3.40282347E+38F
double
1.17549435E–38F to 3.40282347E+38F
long double
1.17549435E–38F to 3.40282347E+38F
• The signed keyword can be omitted. However, with the char type, it is judged as signed char or
unsigned char depending on the condition at compilation.
• short int data and int data are handled as data which have the same value range but are of different
types.
• unsigned short int data and unsigned int data are handled as data which have the same value range
but are of different types.
• float, double, and long double data are handled as data which have the same value range but are of
different types.
(i)
Floating-point number (float type) specifications
• Format
The floating-point number format is shown below.
(Higher address)
s
31 30
e
m
(Lower address)
23 22
0
The numerical values in this format are as follows.
(Value of sign)
(–1)
(Value of exponent)
* (Value of mantissa) *2
s: Sign (1 bit)
0 for a positive number and 1 for a negative number.
e: Exponent (8 bits)
An exponent with a base of 2 is expressed as a 1-byte integer (expressed by two’s complement
in the case of a negative), and used after having a further bias of 7FH added.
relationships are shown in Table 2-4 below.
44
User’s Manual U14872EJ1V0UM
These
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
Table 2-4. Exponent Relationships
Exponent (Hexadecimal)
Value of Exponent
FE
127
•
•
•
•
•
•
81
2
80
1
7F
0
7E
–1
•
•
•
•
•
•
01
–126
m: Mantissa (23 bits)
The mantissa is expressed as an absolute value, with bit positions 22 to 0 equivalent to the 1st to
23rd places of a binary number. Except for when the value of the floating point is 0, the value of
the exponent is always adjusted so that the mantissa is within the range of 1 to 2 (normalization).
The result is that the position of 1 (i.e. the value of 1) is always 1, and is thus represented by
omission in this format.
• Zero expression
When exponent = 0 and mantissa = 0, ±0 is expressed as follows.
(Value of sign)
(–1)
*0
• Infinity expression
When exponent = FFH and mantissa = 0, ±∞ is expressed as follows.
(Value of sign)
*∞
(–1)
• Unnormalized value
When exponent = 0 and mantissa ≠ 0, the unnormalized value is expressed as follows.
(Value of sign)
(–1)
Remark
–126
* (Value of mantissa) *2
The mantissa value here is a number less than 1, so bit
positions 22 to 0 of the mantissa express as is the 1st to
23rd decimal places.
• Not-a-number (NaN) expression
When exponent = FFH and mantissa ≠ 0, NaN is expressed, regardless of the sign.
• Operation result rounding
Numerical values are rounded down to the nearest even number. If the operation result cannot be
expressed in the above floating-point format, round to the nearest expressible number.
If there are two values that can express the differential of the prerounded value, round to an even
number (a number whose lowest binary bit is 0).
User’s Manual U14872EJ1V0UM
45
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
• Operation exceptions
There are five types of operation exceptions, as shown below.
Table 2-5. List of Operation Exceptions
Exception
Return Value
Underflow
Unnormalized number
Inexact
±0
Overflow
±∞
Zero division
±∞
Operation impossible
Not-a-number (NaN)
Calling the matherr function causes a warning to appear when an exception occurs.
(2) Character types
The character data types include the following three types.
• char
• signed char
• unsigned char
(3) Incomplete types
The incomplete data types include the following four types.
• Arrays with indefinite object size
• Structures
• Unions
• void type
(4) Derived types
The derived types are divided into the following three categories.
• Array type
• Structure type
• Union type
• Function type
• Pointer type
(a) Aggregate type
The aggregate type is subdivided into two types.
Array type and Structure type. An aggregate type data is a collection of member objects to be taken
successively.
46
User’s Manual U14872EJ1V0UM
CHAPTER 2
(i)
CONSTRUCTS OF C LANGUAGE
Array type
The array type continuously allocates a collection of member objects called the element type. Member
objects all have an area of the same size. The array type specifies the number of element types and
the elements of the array. It cannot create the array of incomplete type.
(ii) Structure type
The structure type continuously allocates member objects each differing in size. Giving it a name can
specify each member object.
(b) Union type
The union type is a collection of member objects that overlap each other in memory. These member
objects differ in size and name and can be specified individually.
(c) Function type
The function type represents a function that has a specified return value. A function type data specifies the
type of return value, the number of parameters, and the type of parameter. If the type of return value is T,
the function is referred to as a function that returns T.
(d) Pointer type
The pointer type is created from a function type object type called a referenced type as well as from an
incomplete type. The pointer type represents an object. The value indicated by the object is used to
reference the entity of a referenced type.
A pointer type data created from the referenced type T is called a pointer to T.
(5) Scalar types
The arithmetic types (basic type) and pointer type are collectively called the scalar types. The scalar types
include the following data types:
• char type
• Signed integral type
• Unsigned integral type
• Enumeration type
• Floating-point type
• Pointer type
User’s Manual U14872EJ1V0UM
47
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.3.6 Compatible type and composite type
(1) Compatible type
If two types are the same, they are said to be compatible or have compatibility. For example, if two structures,
unions, or enumeration types that are declared in separate translation (compiling) units have the same number
of members, the same member name and compatible member types, they have a compatible type. In this case,
the individual members of the two structures or unions must be in the same order and the individual members
(enumerated constants) of the two enumerated types must have the same values.
All declarations related to the same objects or functions must have a compatible type.
(2) Composite type
A composite type is created from two compatible types. The following rules apply to the composite type.
• If either of the two types is an array of known type size, the composite type is an array of that size.
• If only one of the types is a function type with a parameter type list (declared with a prototype), the composite
type is a function prototype with a parameter type list.
• If both types have a parameter type list (i.e., functions with prototypes), the composite type is the one with a
prototype consisting of all information that can be combined from the two prototypes.
[Example of composite type]
Assume that two declarations that have file scope are as follows.
int f(int(*)(),double(*)[3]);
int f(int(*)(char *),double(*)[]);
The composite type of the function in this case becomes as follows.
int f(int(*)(char *),double(*)[3]);
48
User’s Manual U14872EJ1V0UM
CHAPTER 2
2.4
CONSTRUCTS OF C LANGUAGE
Constants
A constant is a variable that does not change in value during the execution of the program, and its value must be
set beforehand. A type for each constant is determined according to the format and value specified for the constant.
The following four constant types are available.
• Floating-point constants
• Integer constants
• Enumeration constants
• Character constants
2.4.1 Floating-point constant
A floating-point constant consists of a valid digit part, exponent part, and floating-point suffix.
Valid digit part:
Integer part, decimal point, and fraction part
Exponent part:
e or E, signed exponent
Floating point suffix: f/F (float)
I/L (long double)
If omitted (double)
The signed exponent of the exponent part and the floating-point suffix can be omitted.
Either the integer part or fraction part must be included in the valid digits. Also, either the decimal point or
exponent part must be included (example: 1.23F, 2e3).
2.4.2 Integer constant
An integer constant starts with a number and does not have the decimal point or the exponent part. An unsigned
suffix can be added after the integer constant to indicate that the integer constant is unsigned. A long suffix can be
added after the integer constant to indicate that the integer constant is long.
There are the following three types of integer constant.
• Decimal constant:
Decimal number that starts with a number other than 0
Decimal number = 123456789
• Octal constant:
Integer suffix 0 + octal number
Octal number = 01234567
• Hexadecimal constant: Integer suffix 0x or 0X + hexadecimal number
Hexadecimal number = 0123456789
abcdef ABCDEF
Unsigned suffix
u U
Long suffix
l L
(1) Decimal constant
A decimal constant is an integer value with a base (radix) of 10 and must begin with a number other than 0
followed by any numbers 0 through 9 (example: 56U).
User’s Manual U14872EJ1V0UM
49
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(2) Octal constant
An octal constant is an integer value with a base of 8 and must begin with 0 followed by any numbers 0 through
7 (example: 034U).
(3) Hexadecimal constant
A hexadecimal constant is an integer value with a base of 16 and must begin with 0x or 0X followed by any
numbers 0 through 9 and a through f or A through F which represent 10 through 15 (example: 0xF3).
The type of integer constant is regarded as the first of the “representable type” shown below.
In this compiler, the type of the unsubscripted constant can be changed to char or unsigned char depending on
the compile condition (option).
(Integer constant)
(Representable type)
• Unsuffixed decimal number.................................. int, long int, unsigned long int
• Unsuffixed octal, hexadecimal number ................ int, unsigned int, long int, unsigned long int
• Suffixed u or U...................................................... unsigned int, unsigned long int
• Suffixed l or L ....................................................... long int, unsigned long int
• Suffixed u or U, and suffixed l or L ....................... unsigned long int
2.4.3 Enumeration constants
Enumeration constants are used for indicating an element of an enumeration type variable, that is, the value of an
enumeration type variable that can have only the specific value indicated by an identifier.
The enumeration type (enum) is whichever is the first type from the top of the list of three types shown below that
can represent all the enumeration constants. The enumeration constant is indicated by the identifier.
• signed char
• unsigned char
• signed int
It is described as ‘enum enumeration type {list of enumeration constant}’.
Example enum months{January=1,February,March,April,May};
When the integer is specified with =, the enumeration variable has the integer value, and the
following value of enumeration variable has that integer value + 1. In the example shown above, the
enumeration variable has 1, 2, 3, 4, 5, respectively. When there is not ‘= 1’, each constant has 0, 1,
2, 3, 4, 5, respectively.
50
User’s Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.4.4 Character constants
A character constant is one or more character strings enclosed in a pair of single quotes as in ‘X’ or ‘ab’.
A character constant does not include single quote (’), backslash (¥ or \), and line feed character (¥n).
To
represent these characters, escape sequences are used. There are the following three types of escape sequences.
• Simple escape sequence:
• Octal escape sequence:
\’
\”
\?
\¥
\a
\b
\f
\n
\r
\t
\v
\octal number [octal number octal number]
(example: \012, \0
• Hexadecimal escape sequence:
Note 1
)
\x hexadecimal number
Note 2
(example: \xFF
)
Notes 1. Null character
2. In this compiler, \xFF represents –1. If the condition (option) that regards char as unsigned char is
added, however, it represents +255.
2.5
String Literal
A string literal is a string of zero or more characters enclosed in a pair of double quotes as in “xxx” (example:
“xyz”).
A single quote (’) is represented by the single quotation mark itself or by escape sequence \’, whereas a double
quote (”) is represented by escape sequence \”.
Array elements have char type string literal and are initialized by tokens given (example: char array [ ] = “abc”;).
2.6
Operators
The operators are shown below.
[]
()
.
->
++
--
&
*
+
–
~
!
sizeof
/
%
<<
>>
<
>
<=
>=
==
^
|
&&
||
?
:
=
*=
/=
%=
+=
-=
<<=
>>=
&=
^=
|=
,
#
##
!=
The [ ], ( ), and ?: operators must always be used in pairs.
An expression may be described in brackets “[ ]”, in parentheses “( )”, or between “?” and “:”.
The # and ## operators are used only for defining macros in preprocessing directives. (For the description, refer
to CHAPTER 5 OPERATORS AND EXPRESSIONS.)
User’s Manual U14872EJ1V0UM
51
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.7 Delimiters
A delimiter is a symbol that has an independent syntax or meaning. However, it never generates a value.
The following delimiters are available for use in C.
[]
()
{}
*
,
:
=
;
...
#
An expression declaration or statement may be described in brackets “[ ]”, parentheses “( )”, or braces “{ }”.
These delimiters must always be used in pairs as shown above. The delimiter # is used only for preprocessing
directives.
2.8
Header Name
The header name indicates the name of an external source file. This name is used only in the preprocessing
directive “#include”.
An example of an #include instruction of a header name is shown below. For the details of each #include
instruction, refer to 9.2 Source File Inclusion Directive.
#include <header name>
#include “header name”
2.9
Comment
A comment refers to a statement to be included in a C source module for information only. It begins with “/*” and
ends with “*/”. The part after “//” to the line feed can be identified as a comment statement by the -ZP option.
Example
/* comment statement */
//comment statement
52
User’s Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
This chapter explains how data (variables) or functions to be used in C should be declared as well as the scope for
each data or function. A declaration means the specification of an interpretation or attribute for an identifier or a
collection of identifiers. A declaration to reserve a storage area for an object or function named by an identifier is
referred to as a “definition”.
An example of a declaration is shown below.
#define TRUE
1
#define FALSE 0
#define SIZE
200
void main(void)
{
auto int i,prime,k;
/* declaration of automatic variables */
for(i=0;i<=SIZE;i++)
mark[i]=TRUE;
.
.
.
A declaration consists of a storage class specifier, type specifier, initialize declarator, etc. The storage class
specifier and type specifier specify the linkage, storage duration, and the type of entity indicated by the declarator.
An initialize declarator list is a list of declarators each delimited with a comma. Each declarator may have additional
type information or an initializer or both.
If an identifier for an object declares that it has no linkage, the type for the object must be perfect (the object with
information related to the size) at the end of the declarator or initialize declarator (if there is any).
User’s Manual U14872EJ1V0UM
53
CHAPTER 3
3.1
DECLARATION OF TYPES AND STORAGE CLASSES
Storage Class Specifiers
A storage class specifier specifies the storage class of an object. It indicates the storage location of the value that
the object has, and the scope of the object. In a declaration, only one storage class specifier can be described. The
following five storage class specifiers are available.
• typedef
• extern
• static
• auto
• register
(1) typedef
The typedef specifier declares a synonym for the specified type. See 3.6 typedef for details of the typedef
specifier.
(2) extern
The extern specifier indicates (tells the compiler) that a variable immediately before this specifier is declared
elsewhere in the program (i.e., an external variable).
(3) static
The static specifier indicates that an object has static storage duration. For an object that has static storage
duration, an area is reserved before the program execution and the value to be stored is initialized only once.
The object exists throughout the execution of the entire program and retains the value last stored in it.
(4) auto
The auto specifier indicates that an object has automatic storage duration. For an object that has automatic
storage duration, an area is reserved when the object enters a block to be declared.
At entry into the declared block from its top, the object is initialized if so specified. If the object enters the block
by jumping to a label within the block, the object will not be initialized.
The area reserved for an object with automatic storage duration will not be guaranteed after the execution of the
declared block.
(5) register
The register specifier indicates that an object is assigned to a register of the CPU. With this C compiler, it is
allocated to the register or saddr area of the CPU. See CHAPTER 11 EXTENDED FUNCTIONS for details of
register variables.
54
User’s Manual U14872EJ1V0UM
CHAPTER 3
3.2
DECLARATION OF TYPES AND STORAGE CLASSES
Type Specifiers
A type specifier specifies (or refers to) the type of an object. The following type specifiers are available.
• void
• char
• short
• int
• long
• float
• double
• long double
• signed
• unsigned
• Structure or union specifier
• Enumeration specifier
• typedef name
In this C compiler, the following type specifiers have been added.
• bit/boolean/_ _boolean
User’s Manual U14872EJ1V0UM
55
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
The following is an explanation of the meaning of each type specifier and the limit values that can be expressed
with this compiler (the values enclosed in the parentheses). Since this compiler supports only the single precision of
IEEE Std 754-1985 for floating-point operations, double and long double data are regarded as having the same
format as float data.
• void .................................................................... Collection of null values
• char .................................................................... Size of the basic character set that can be stored
• signed char ..................................................... Signed integer (–128 to +127)
• unsigned char ................................................. Unsigned integer (0 to 255)
• short, signed short, short int,
signed short int........................................... Signed integer (–32768 to +32767)
• unsigned short, unsigned short int .... Unsigned integer (0 to 65535)
• int, signed, signed int............................ Signed integer (–32768 to +32767)
• unsigned, unsigned int.............................. Unsigned integer (0 to 65535)
• long, signed long, long int,
signed long int............................................. Signed integer (–2147483648 to +2147483647)
• unsigned long, unsigned long int ........ Unsigned integer (0 to 4294967295)
• float .................................................................. Single-precision floating-point number (1.17549435E–38F to
3.40282347E+38F)
• double ................................................................ Double-precision floating-point number (1.17549435E–38F
to 3.40282347E+38F)
• long double ..................................................... Extended precision floating point number
(1.17549435E–38F to 3.40282347E+38F)
• Structure/union specifier ...................................... Collection of member objects
• Enumeration specifier .......................................... Collection of int type constants
• typedef name .................................................... Synonym of specified type
• bit, boolean, _ _boolean.......................... Integers represented with a single bit (0 to 1)
Type specifiers separated from each other with a slash have the same size.
56
User’s Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.2.1 Structure specifier and union specifier
Both the structure specifier and union specifier indicate a collection of named members (objects). These member
objects can have different types from one another.
(1) Structure specifier
The structure specifier declares a collection of two or more different types of variables as one object. Each type
of object is called a member and can be given a name. For members, continuous areas are reserved in the
order of their declarations.
However, because the 78K/0S Series contains a restriction whereby word data is unable to be read from or
written to odd addresses, the code size is prioritized by default, and align data is inserted to ensure members of
2 bytes or more are allocated to even addresses. Gaps may therefore occur between members due to the align
data.
The -RC option can be specified to inhibit insertion of align data and enable structures to be packed. In this
case, although the size of the data is reduced, members of 2 or more bytes allocated to odd addresses are
read/written using 1-byte unit read/write code, which increases the code size.
The structure is declared as follows. The declaration will not yet allocate memory since it does not have a list of
structure variables. For the definition of the structure variables, refer to CHAPTER 7 STRUCTURES AND
UNIONS.
struct identifier {member declaration list};
Example of structure declaration
struct tnode{
int count;
struct tnode *left,*right;
};
(2) Union specifier
The union specifier declares a collection of two or more different types of variables as one object. Each type of
object is called a member and can be given a name. The members of a union overlay each other in area,
namely, they share the same area.
The union is declared as follows. The declaration will not yet allocate memory since it does not have a list of
union variables. For the definition of the union variables, refer to CHAPTER 7 STRUCTURES AND UNIONS.
union identifier {member declaration list};
Example of union declaration
union u_tag{
int var1 ;
long var2 ;
};
Each member object can be any type other than the incomplete types or function types. The member can be
declared with the number of bits specified. The member with the number of bits specified is called a bit field.
User’s Manual U14872EJ1V0UM
57
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
In this compiler, extended functions related to bit field declaration have been added. For details, refer to 11.5
(14) Bit field declaration.
(3) Bit field
A bit field is an integral type area consisting of a specified number of bits. For the bit field, int type, unsigned
int type, and signed int type data can be specified.
signed int field will be judged as a sign bit.
Note 1
The MSB of an int field which has no qualifier or a
Note 2
If two or more bit fields exist, the second and subsequent bit fields are packed into the adjacent bit positions,
provided there is sufficient space within the same memory unit. By placing an unnamed bit field with a width of
0, the next bit field will not be packed into a space within the same memory unit. An unnamed bit field has no
declarator and declares a colon and a width only.
Unary&operator (address) cannot be applied to the bit field object.
Notes 1. In this compiler, char type, unsigned char type, and signed char type can also be specified. All of
them are regarded as unsigned type since this compiler does not support signed type bit field.
2. In this compiler, the direction of bit field allocation can be changed by compiler option -RB (for
details, refer to CHAPTER 11 EXTENDED FUNCTIONS).
The following shows an example of a bit field.
struct data{
unsigned int a:2;
unsigned int b:3;
unsigned int c:1;
}no1;
58
User’s Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.2.2 Enumeration specifiers
An enumeration type specifier indicates a list of objects to be put in sequence. Objects to be declared with the
enum specifier will be declared as constants that have int types.
The enumeration specifier is declared as shown below.
enum identifier {enumerator list}
Objects are declared with an enumerator list. Values are defined for all objects in the list in the order of their
declaration by assigning the value of 0 to the first object and the value of the previous object plus 1 to the 2nd and
subsequent objects. A constant value may also be specified with “=”.
In the following example, “hue” is assumed as the tag name of the enumeration, “col” as an object that has this
(enum) type, and “cp” as a pointer to an object of this type. In this declaration, the values of the enumeration
become “{0, 1, 20, 21}”.
enum hue{
chartreuse,
burgundy,
claret=20,
winedark
};
enum hue col,*cp;
void main(void) {
col=claret;
cp=&col ;
/*...*/ (*cp!=burgundy) /*...*/
.
.
.
User’s Manual U14872EJ1V0UM
59
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.2.3 Tags
A tag is a name given to a structure, union, or enumeration type. A tag has a declared data type and objects of
the same type can be declared with a tag.
The identifier in the following declaration is a tag name.
structure/union
identifier {member declaration list}
or
enum identifier {enumerator list}
A tag contains the contents of the structure/union or enumeration defined by a member.
In the next and
subsequent declarations, the structure of a struct, union, or enum type becomes the same as that of the tag’s list. In
the subsequent declarations within the same scope, the list enclosed in braces must be omitted. The following type
specifier is undefined with respect to its contents and thus the structure or union has an incomplete type.
structure/union
identifier
A tag to specify the type of this type specifier can be used only when the object size is unnecessary. The reason
is that by defining the contents of the tag within the same scope, the type specification becomes incomplete.
In the following example, the tag “tnode” specifies a structure that includes pointers to an integer and two objects
of the same type.
struct tnode{
int count;
struct tnode *left,*right;
};
The next example declares “s” as an object of the type indicated by the tag (tnode) and “sp” as a pointer to the
object of the type indicated by the tag. By this declaration, the expression “sp → left” indicates a pointer to “struct
tnode” on the left of the object pointed to by “sp” and the expression “s.right → count” indicates “count” which is a
member of “struct tnode” on the right of “s”.
typedef struct tnode TNODE;
struct tnode{
int count;
struct tnode *left,*right;
};
TNODE s *sp;
void main(void){
sp->left=sp->right;
s.right->count=2;
}
60
User’s Manual U14872EJ1V0UM
CHAPTER 3
3.3
DECLARATION OF TYPES AND STORAGE CLASSES
Type Qualifiers
Two type qualifiers are available: const and volatile. These type qualifiers affect left-side values only.
Using a left-side value that has non-const type qualifier cannot change an object that has been defined with const
type qualifier. Using a left-side value that has non-volatile type qualifier cannot reference an object that has been
defined with volatile type qualifier.
An object that has volatile qualifier type can be changed by a method not recognizable by the compiler or may
have other unnoticeable side effects. Therefore, an expression that references this object must be strictly evaluated
according to the sequence rules that regulate abstractly how programs written in C should be executed. In addition,
the values to be last stored in the object at every sequence point must be in agreement with those determined by the
program except the changes due to the factors unrecognizable by the compiler as mentioned above.
If an array type is specified with type qualifiers, the qualifiers apply to the array members, not the array itself.
No type qualifier can be included in the specification of a function type. However, callt, _ _ callt, callf, _ _ callf,
noauto, norec, _ _ leaf, _ _ interrupt, _ _ interrupt_brk, _ _rtos_interrupt, _ _pascal, which are the type qualifiers
unique to this compiler mentioned in 2.2 Keywords, can be included as type qualifiers.
sreg, _ _sreg, _ _directmap, and _ _temp are also type qualifiers.
In the following example, “real_time_clock” can be changed by hardware, but operations such as assignment,
increment, and decrement are not allowed.
extern const volatile int real_time_clock;
An example of modifying aggregate type data with type qualifiers is shown below.
const struct s{int mem;} cs={1};
struct s ncs;
/* object ncs is changeable */
typedef int A[2][3];
const A a={{4,5,6},{7,8,9}};
/* array of const int array */
int *pi;
const int *pci;
ncs=cs;
/* correct */
cs=ncs;
/* violates restriction of Lvalue which has modifiable assignment operator */
pi=&ncs.mem;
/* correct */
pi=&cs.mem;
/* violates restriction of the type of assignment operator = */
pci=&cs.mem;
/* correct */
pi=a[0];
/* incorrect:a[0] has “const int *” type */
User’s Manual U14872EJ1V0UM
61
CHAPTER 3
3.4
DECLARATION OF TYPES AND STORAGE CLASSES
Declarators
A declarator declares an identifier. Here, pointer declarators, array declarators, and function declarators are
mainly discussed. The scope of an identifier and a function or object which has a storage duration and a type are
determined by declarators.
A description of each declarator is provided below.
3.4.1 Pointer declarators
A pointer declarator indicates that an identifier to be declared is a pointer. A pointer points to (indicates) the
location where a value is stored. Pointer declarations are performed as follows.
* type qualifier list
identifier
By this declaration, the identifier becomes a pointer to T1.
The following two declarations indicate a variable pointer to a constant value and an invariable pointer to a
variable value, respectively.
const int *ptr_to_constant;
int *const constant_ptr;
The first declaration indicates that the value of the constant “const int” pointed by the pointer “ptr_to_constant”
cannot be changed, but the pointer “ptr_to_constant” itself may be changed to point to another “const int”. Likewise,
the second declaration indicates that the value of the variable “int” pointed by the pointer “constant_ptr” may be
changed, but the pointer “constant_ptr” itself must always point to the same position.
The declaration of the invariable pointer “constant_ptr” can be made distinct by including a definition for the pointer
type to the int type data.
The following example declares “constant_ptr” as an object that has a const qualifier pointer type to int.
typedef int *int_ptr;
const int_ptr constant_ptr;
62
User’s Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.4.2 Array declarators
An array declarator declares to the compiler that an identifier to be declared is an object that has an array type.
Array declaration is performed as shown below.
type
identifier [constant expression]
By this declaration, the identifier becomes an array that has the declared type.
The value of the constant
expression becomes the number of elements in the array. The constant expression must be an integer constant
expression which has a value greater than 0. In the declaration of an array, if a constant expression is not specified,
the array becomes an incomplete type.
In the following example, a char type array “a[ ]” which consists of 11 elements and a char type pointer array
“ap[ ]” which consists of 17 elements have been declared.
char a[11],*ap[17];
In the following two examples of declarations, “x” in the first declaration specifies a pointer to an int type data and
“y” in the second declaration specifies an array to an int type data which has no size specification and is to be
declared elsewhere in the program.
extern int *x;
extern int y[];
3.4.3 Function declarators (including prototype declarations)
A function declarator declares the type of return value, argument, and the type of the argument value of a function
to be referenced.
Function declaration is performed as follows.
type
identifier (parameter list or identifier list)
By this declaration, the identifier becomes a function which has the parameter specified by the parameter type list
and returns the value of the type declared before the identifier.
Parameters of a function are specified by a
parameter identifier lists. By these lists, an identifier, which indicates argument and its type, are specified. A macro
defined in the header file “stdarg.h” converts the list described by the ellipsis (, ...) into parameters. For a function
that has no parameter specification, the parameter list will become “void”.
User’s Manual U14872EJ1V0UM
63
CHAPTER 3
3.5
DECLARATION OF TYPES AND STORAGE CLASSES
Type Names
A type name is the name of the data type that indicates the size of a function or object. Syntax-wise, it is a
function or object declaration less identifiers.
Examples of type names are given below.
• int ................................................... Specifies an int type.
• int *................................................. Specifies a pointer to an int type.
• int *[3]............................................. Specifies an array which has three pointers to an int type.
• int (*) [3] ......................................... Specifies a pointer to an array which has three int types.
• int *( ) ............................................ Specifies a function which returns a pointer to an int type which has no
parameter specification.
• int (*) (void) .................................... Specifies a pointer to a function which returns an int type which no
parameter specification.
• int (*const [ ]) (unsigned int, ...) ... Specifies an indefinite number of arrays which have one parameter of
unsigned int type and an invariable pointer to each function that returns an int
type.
64
User’s Manual U14872EJ1V0UM
CHAPTER 3
3.6
DECLARATION OF TYPES AND STORAGE CLASSES
typedef Declarations
The typedef keyword defines that an identifier is synonymous with a specified type.
The defined identifier
becomes a typedef name.
The syntax of typedef names is shown below.
typedef type identifier;
In the following example, “distance” is an int type, the type of “metricp” is a pointer to a function that returns an
int type that has no parameter specification, the type of “z” is a specified structure, and “zp” is a pointer to this
structure.
typedef int MILES,KLICKSP();
typedef struct{long re,im} complex;
/*...*/
MILES distance;
extern KLICKSP *metricp;
complex z,*zp;
In the following example, typedef name t is declared with signed int type, and typedef name plain is declared with
int type, respectively, and the structure with three bit field members is declared. The bit field members are as
follows.
• Bit field member with name t and the value 0 to 15
• Bit field member without a name and the const qualified value –16 to +15 (if accessed)
• Bit field member with name r and the value –16 to +15
typedef signed int t;
typedef int plain;
struct tag{
unsigned t:4;
const t:5;
plain r:5;
};
In this example, these two bit field declarations differ in the point that the first bit field declaration has unsigned as the
type specifier (therefore, t becomes the name of the structure member), and the second bit field declaration, has
const as the type qualifier (qualifiers t which can be referred to as typedef name). After this declaration, if:
t f(t(t));
long t;
is found within the valid range, the function f is declared as “function which has one parameter and returns signed
int”, and the parameter is declared as “pointer type for the function which has one parameter and returns signed int”.
The identifier t is declared as long type.
User’s Manual U14872EJ1V0UM
65
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
typedef names may be used to facilitate program reading. For example, the following three declarations for the
function signal all specify the same type as the first declaration that does not use typedef.
typedef void fv(int);
typedef void (*pfv)(int);
void(*signal(int,void(*)(int)))(int);
fv *signal(int,fv *);
pfv signal(int,pfv);
66
User’s Manual U14872EJ1V0UM
CHAPTER 3
3.7
DECLARATION OF TYPES AND STORAGE CLASSES
Initialization
Initialization refers to setting a value in an object beforehand. Initializers carry out the initialization of an object.
Initialization is performed as follows.
object = {initializer list}
An initializer list must contain initializers for the number of objects to be initialized.
All expressions in initializers or an initializer list for objects that have static storage duration and objects that have
an aggregate type or a union type must be specified with constant expressions.
Identifiers that declare block scope but have external or internal linkage cannot be initialized.
(1) Initialization of objects which have a static storage duration
If no attempt is made to initialize an arithmetic type object that has static storage duration, the value of the object
will be implicitly initialized to 0.
Likewise, a pointer type object which has a static storage duration will be initialized to a null pointer constant.
Example
unsigned int gval1;
/* initialized by 0 */
static int gval2;
/* initialized by 0 */
void func(void){
static char aval;
/* initialized by 0 */
}
(2) Initialization of objects which have an automatic storage duration
The value of an object which has an automatic storage duration becomes indefinite and will not be guaranteed if
it is not initialized.
Example
void func(void){
char aval;
/*undefined at this point */
.
.
.
aval=1;
/* initialized to 1 */
}
(3) Initialization of character arrays
A character array can be initialized with a character string literal (character string enclosed in “ ”). Likewise, a
character string in which a series of character string literals are contained initializes the individual members or
elements of an array.
In the following example, the array objects “s” and “t” with no type qualifier are defined and the elements of each
array will be initialized by character string literal.
char s[]="abc",t[3]="abc";
The next example is the same as the above example of array initialization.
User’s Manual U14872EJ1V0UM
67
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
char s[]={'a','b','c','\0'},
t[]={'a','b','c'};
The next example defines p as “pointer to char” type and the member is initialized by character string literal so
that the length indicates a “char array” type object.
char *p="abc";
(4) Initialization of aggregate or union type objects
• Aggregate type
An aggregate type object is initialized with a list of initializers described in ascending order of subscripts or
members. The initializer list to be specified must be enclosed in braces.
If the number of initializers in the list is less than the number of aggregate members, the members not
covered by the initializers will be implicitly initialized just the same as an object which has a static storage
duration.
With an array of unknown size, the number of elements is governed by the number of initializers and the array
will no longer become an incomplete type.
• Union type
A union type object is initialized of initializer for the first member of the union that is enclosed in braces.
In the following example, the array “x” of unknown size will change to a one-dimensional array that has three
elements as a result of its initialization.
int x[]={1,3,5};
The next example shows a complete definition which has initializers enclosed in braces. “{1, 3, 5}” initializes
“y [0] [0]”, “y [0] [1]”, and “y [0] [2]” in the 1st line of the array object “y[0]”. Likewise, in the second line, the
elements of the array objects “y [1]” and “y [2]” are initialized. The initial value of “y[3]” is 0 since it is not
specified.
char y[4][3]={
{1,3,5},
{2,4,6},
{3,5,7},
};
The next example produces the same result as the above example.
char z[4][3]={
1,3,5,2,4,6,3,5,7
};
In the following example, the elements in the first row of “z” are initialized to the specified values and the rest of
the elements are initialized to 0.
68
User’s Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
char z[4][3] = {
{1}, {2}, {3}, {4}
};
In the next example, a three-dimensional array is initialized.
q[0] [0] [0] are initialized to 1, q[1] [0] [0] to 2, and q[1] [0] [1] to 3. 4, 5 and 6 initialize q[2] [0] [0], q[2] [0] [1], and
q[2] [1] [0], respectively. The rest of the elements are all initialized to 0.
short q[4][3][2] = {
{1},
{2, 3}
{4, 5, 6}
};
The following example produces the same result as the above initialization of the three-dimensional array.
short q[4][3][2] = {
1, 0, 0, 0, 0, 0,
2, 3, 0, 0, 0, 0,
4, 5, 6
};
The following example shows a complete definition of the above initialization using braces.
Short q[4][3][2] = {
{
{1},
},
{
{2, 3},
},
{
{4, 5, 6},
}
};
User’s Manual U14872EJ1V0UM
69
CHAPTER 4
TYPE CONVERSIONS
In an expression, if two operands differ in data type, the compiler automatically performs a type conversion
operation. This conversion is similar to the change obtained by the cast operator. This automatic type conversion is
called an implicit type conversion. In this chapter, this implicit type conversion is explained.
Type conversion operations include usual arithmetic conversions, conversions involving truncation/round off, and
conversions involving sign change. A list of conversions between types is shown in Table 4-1.
70
User’s Manual U14872EJ1V0UM
CHAPTER 4
TYPE CONVERSIONS
Table 4-1. List of Conversions Between Types
After Conversion (signed) unsigned (signed)
char
char
short int
Before Conversion
(signed) char
+
{
{
{
{
{
{
{
{
{
{
–
N
{
N
{
N
{
N
{
{
{
{
{
{
{
{
{
{
{
{
∆
unsigned char
(signed) short int
+
{
{
{
{
{
{
{
–
N
N
{
N
{
{
{
{
{
{
{
{
∆
unsigned short int
(signed) int
unsigned (signed) unsigned (signed) unsigned float double long
short int int
int
long int long int
double
∆
+
{
{
{
{
{
{
{
–
N
N
{
N
{
{
{
{
{
{
{
{
+
{
{
{
{
–
N
{
{
{
{
{
{
{
{
∆
unsigned int
(signed) long int
∆
∆
unsigned long int
float
double
long double
Remarks 1. The signed keyword can be omitted. However, with a char type data, the data type is regarded as the
signed char or unsigned char type depending on the compile-time condition (option).
2. Conventions
{:
Type conversion will be performed properly.
\:
Type conversion will not be performed.
N:
A correct value will not be generated. (The data type will be regarded as an unsigned int type.)
∆:
The data type will not change bit-image-wise. However, if a positive number cannot represent it
sufficiently, no correct value will be generated (regarded as an unsigned integer)
Blank:An overflow in the result of the conversion will be truncated. The + or – sign of the data may be
changed depending on the type after the conversion.
User’s Manual U14872EJ1V0UM
71
CHAPTER 4
4.1
TYPE CONVERSIONS
Arithmetic Operands
(1) Characters and integers (general integral promotion)
The data types of char, short int, and int bit fields (whether they are signed or unsigned) or of objects that have
an enumeration type will be converted to int types if their values are within the range that can be represented
with int types.
If not within the range, they will be converted to unsigned int types.
conversions are referred to as “general integral general promotion”.
These implicit type
All other arithmetic types will not be
changed by this general integral promotion.
General integral promotion will retain the value of the original data type including its sign.
char type data without a type qualifier will normally be handled as signed char in this compiler. It can be
handled as an unsigned char using an option.
(2) Signed integers and unsigned integers
When a value with an integer type is converted to another, the value will not be changed if the value can be
expressed with the integer type after conversion.
When a signed integer is converted to an unsigned integer of the same or larger size, the value is not changed
unless the value of the signed integer is negative. If the value of the signed integer is negative and the unsigned
integer has a size larger than that of the signed integer, the signed integer is expanded to the signed integer with
the same size as the unsigned integer, and then it is added with the value equal to the maximum number that
can be expressed with the unsigned integer plus 1, and the signed integer before conversion is converted to the
unsigned value.
When a value with an integer type is converted to an unsigned integer with a smaller size, the conversion result
is a non-negative remainder which the value is divided with that value which 1 is added to the maximum number
that can be expressed with an unsigned integer after conversion.
When a value with an integer type is
converted to a signed integer with smaller size or when an unsigned integer is converted to a signed integer with
the same size, the overflown value is ignored if the value after conversion cannot be expressed.
For the
conversion pattern, refer to Table 4-1. List of Conversions Between Types.
Conversion operations from signed integral type to unsigned integral type are as listed in Table 4-2 below.
Table 4-2. Conversions from Signed Integral Type to Unsigned Integral Type
unsigned
Smaller in Value Range
Greater in Value Range
+
/
{
–
/
+
signed
{:Type conversion will be performed properly.
+: The data will be converted to a positive integer.
/: The result of the conversion will be the remainder of the integer value,
modulo the largest possible value of the type to be converted plus 1.
72
User’s Manual U14872EJ1V0UM
CHAPTER 4
TYPE CONVERSIONS
(3) Usual arithmetic type conversions
Types obtained as a result of operations on arithmetic type data will have a wide range of values.
The type conversion of the operation result is performed as follows.
• If either one of the operands has long double type, the other operand is converted to long double type.
• If either one of the operands has double type, the other operand is converted to double type.
• If either one of the operands has float type, the other operand is converted to float type.
In cases other than above, general integer expansion is performed for both operands according to the following
rules. Figure 4-1 shows the rules.
Figure 4-1. Usual Arithmetic Type Conversions
unsigned long int
......................... If either of the two operands is unsigned long int type, or with one
operand being long int type and the other being unsigned int type,
if the value of unsigned int type cannot represented by long int type,
both operands will be converted to unsigned long int type.
long int
unsigned int
......................... In cases other than above, if one operand is long int type and if the value of
the other operand can be represented by long int type, the other operand will be
converted to long int type.
......................... In cases other than above, if one operand is unsigned int type, the other operand
will be converted to unsigned int type.
int
......................... In cases other than above, both operands will have int type.
In this compiler, the conversion to int type can be intentionally disabled by compile condition (optimizing option)
(For the details, refer to CC78K0S C Compiler Operation (U14871E) CHAPTER 5 COMPILER OPTION).
User’s Manual U14872EJ1V0UM
73
CHAPTER 4
4.2
TYPE CONVERSIONS
Other Operands
(1) Left-side values and function locators
A left-side value refers to an expression that specifies an object (and has an incomplete type other than object
type or void type).
Left-side values that do not have array types, incomplete types, or const qualifier types, and structures or unions
which have no const qualifier type members are “modifiable left-side values”.
A left-side value which has no array type will be converted to a value stored in the object to be specified, except
when it is the operand of the sizeof operator, unary & operator, ++ operator, or - - operator or the left operand of
an operator or an assignment operator. By being converted, it will no longer serve as a left-side value.
The behavior of left-side values that have incomplete types but no array types will not be guaranteed.
A left-side value which has an “... array” type except character arrays will be converted to an expression which
has a “pointer to ...” type. This expression is no longer a left-side value.
A function locator is an expression that has a function type. With the exception of the operand of the sizeof
operator or unary & operator, a function locator that has a “function type that returns ...” will be converted to an
expression that has a “pointer type to a function that returns ...”.
(2) void
The value (non-existent) of a void expression (i.e., an expression that has the void type) cannot be used in any
way. Neither implicit nor explicit conversion to exclude void will be applied to this expression. If an expression
of another type appears in the context which requires a void expression, the value of the expression or specifier
is assumed to be non-existent.
(3) Pointers
A void pointer can be converted to a pointer to any incomplete type or object type. Conversely, a pointer to any
incomplete type or object type can be converted to a void pointer. In either case, the result value must be equal
to that of the original pointer.
An integer constant expression which has the value of 0 and has been cast to the void * type is referred to as a
“null pointer constant”. If the null pointer constant is substituted with, equal to, or compared with some pointer,
the null pointer constant will be converted to that pointer.
74
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
This chapter describes the operators and expressions to be used in the C language.
C has an abundance of operators for arithmetic, logical, and other operations. This rich set of operators also
includes those for bit and address operations.
An expression is a string or combination of an operator and one or more operands. The operator defines the
action to be performed on the operand(s) such as computation of a value, instructions on an object or function,
generation of side effects, or a combination of these.
Examples of operators are given below.
#define TRUE
1
#define FALSE 0
#define SIZE
200
void lprintf(char*, int);
void putchar(char c);
char mark[SIZE+1];
+ .............................................................
Arithmetic operator
void main(void){
int i,prime,k,count;
count=0;
= .............................................................
Assignment operator
for(i=0;i<=SIZE;i++)
++ ...........................................................
Postfix operator
<= ...........................................................
Relational operator
+ ............................................
Arithmetic operator
count++;
++ ..........................................
Postfix operator
if((count%8)==0)
== ..........................................
Relational operator
mark[i]=TRUE;
for(i=0;i<=SIZE;i++){
if(mark[i]){
prime=i+i+3;
lprintf("%d",prime);
putchar('\n');
for(k=i+prime;k<=SIZE;k+=prime)
+=....................
Assignment operator
mark[k]=FALSE;
}
}
User’s Manual U14872EJ1V0UM
75
CHAPTER 5
lprintf(“Total
OPERATORS AND EXPRESSIONS
%d\n”, count);
loop1:
goto loop1;
}
lprintf(char *s,int;){
int j;
char *ss;
j=i;
ss=s;
}
void puttchar(char c){
char d;
d=c;
}
76
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
Table 5-1 shows the evaluation precedence of operators used in C.
Table 5-1. Evaluation Precedence of Operators
Type of Expression
Operator
Linkage
Postfix
[ ] ( ) . – > ++ – –
→
Unary
++ – – & * + – ~ ! sizeof
←
Cast
(type)
←
Multiplicative
* / %
→
Additive
+–
→
Bitwise shift
<< >>
→
Relational
< > <= >=
→
Equality
== !=
→
Bitwise AND
&
→
Bitwise XOR
^
→
Bitwise OR
|
→
Logical AND
&&
→
Logical OR
| |
→
Conditional
? :
←
Assignment
= *= /= %= += –=
<<= >>= &= ^= | =
←
Comma
,
→
Priority
Highest
Lowest
Operations in the same line contain the same priority.
The arrow (→ or ←) in the Linkage column denotes that when an expression contains two or more operators of the
same precedence, the operations are carried out in the direction of the arrow “→” (from left to right) or “←” (from right
to left).
User’s Manual U14872EJ1V0UM
77
CHAPTER 5
5.1
OPERATORS AND EXPRESSIONS
Primary Expressions
Primary expressions include the following.
• Identifier declared as an object or function
(identifier primary expression)
• Constant (constant primary expression)
• String literal (constant primary expression)
• Expression enclosed in parentheses
(parenthesized expression)
An identifier which becomes a primary expression is a left-side value if an object is declared or a function locator if
a function is declared. The data type of a constant is determined according to the value specified for the constant as
explained in 2.4 Constants. String literal(s) become a left-side value that has a data type as explained in 2.5 String
Literal.
5.2
Postfix Operators
A postfix operator is an operator that appears or is placed after an object or function.
The primary expressions are explained on the following pages.
78
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Subscript operator
Postfix Operators
[ ] Subscript Operator
FUNCTION
The [ ] subscript operator specifies or refers to a single member of an array object. The array or expression “E1
[E2]” is evaluated as if it were “(*(E1+(E2)))”. In other words, the value of E1 is a pointer to the first member of
the array and E2 (if it is an integer) indicates the E2th member of E1 (counting from 0). With a multidimensional
array, as many subscript operators as the number of dimensions must be connected.
In the following example, x becomes an int type array of 3*5. In other words, x is an array which has three
members each consisting of five int type members.
int x[3][5];
A multidimensional array may be specified by connecting subscript operators. Assuming that E is an array of nth
dimension (where n ≥ 2) consisting of i*j*...*k, the array can be specified with the n number of subscript
operators. In this case, E becomes a pointer to an array of (n – 1)th dimension consisting of j*...*k.
SYNTAX
postfix-expression [subscripted expression]
NOTE
A postfix expression must have a “.... pointer to object”. The subscripted expression of an array must be
specified with integral type data. The result of the expression will become “.....” type.
User’s Manual U14872EJ1V0UM
79
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Function call
Postfix Operators
( ) Function Call
FUNCTION
The postfix operator ( ) calls a function. The function to be called is specified with a postfix expression and
argument(s) to passed to the function are indicated in parentheses ( ).
The description related to the function includes the function prototype declaration, the function definition (the
body of the function), and the function call. The function prototype declaration specifies the value a function
returns, the type of argument, and the storage class.
If the function prototype declaration is not referred to in a function call, each argument is extended with a general
integer. This is called “default actual argument extension”. Performing a function prototype declaration avoids
default actual argument extension and detects the mistakes of the type and number of arguments and the type
of the return value.
Calling a function which has neither a storage class specification nor a data type specification such as “identifier
();” is interpreted as calling a function which has an external object and returns an int type which has no
information on arguments. In other words, the following declaration will be made implicitly:
extern int identifier ();
SYNTAX
postfix-expression ( argument-expression list );
[Example of function call]
int func(char,int);
/* function prototype declaration */
char a;
int b,ret;
void main(void){
ret=func(a,b);
/* function call */
}
int func(char c, int i){
/* function definition */
.
.
.
return i;
}
NOTE
A function that returns an object other than array types can be called with this operator. The postfix expression
must be of a pointer type to this function.
In a function call including a prototype, the type of argument must be of a type that can be assigned to the
corresponding parameter(s). The number of arguments must also be in agreement.
80
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(3) Structure and union member
Postfix Operators
. ->
<1> . (dot) operator
FUNCTION
The . (dot) operator (also called a member operator) specifies the individual members of a structure or union.
The postfix expression is the name of the structure or union object to be specified, and the identifier is the name
of the member.
SYNTAX
postfix-expression . identifier
<2> -> (arrow) operator
FUNCTION
The −> (arrow) operator (also called an indirect membership operator) specifies the individual members of a
structure or union. The postfix expression is the name of the pointer to the structure or union object to be
specified, and the identifier is the name of the member.
SYNTAX
postfix-expression -> identifier
User’s Manual U14872EJ1V0UM
81
CHAPTER 5
OPERATORS AND EXPRESSIONS
Postfix Operators
. ->
[Examples of ‘.’, ‘->’ operators]
#include <stdlib.h>
union{
struct{
int type;
}n;
struct{
int type;
int intnode;
}ni;
struct {
int type;
struct{
long longnode;
}*nl_p;
}nl;
}u;
void func(void){
u.nl.type=1;
u.nl.nl_p->longnode=-31415L;
/*...*/
if(u.n.type==1)
u.nl.nl_p->longnode=labs(u.nl.nl_p->longnode);
}
82
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(4) Postfix increment/decrement operators
Postfix Operators
++ – –
<1> Postfix increment operator
FUNCTION
The postfix increment operator increments the value of an object by 1. This increment operation is performed by
taking the data type of the object into account.
SYNTAX
postfix-expression ++
<2> Postfix decrement operator
FUNCTION
The postfix decrement operator decrements the value of an object by 1. This decrement operation is performed
by taking the data type of the object into account.
SYNTAX
postfix expression ––
NOTE
The operand of the postfix increment or decrement operator must be a modifiable Lvalue
(qualified or
unqualified).
User’s Manual U14872EJ1V0UM
83
CHAPTER 5
5.3
OPERATORS AND EXPRESSIONS
Unary Operators
A unary operator performs an operation on one object or parameter (i.e., operand). The following unary operators
are available.
• Prefix increment and decrement operators
++ ––
• Address and indirect operators
& *
• Unary arithmetic operators
+
–
~
!
• sizeof operator
sizeof
The unary operators are explained in the following pages.
84
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Prefix increment/decrement operators
Unary Operators
++ – –
<1> Prefix increment operator
FUNCTION
The prefix increment operator increments the value of an object by 1. The expression “++E” of the prefix
increment operator will produce the same result as the following expression.
E = E + 1
or
E += 1
SYNTAX
++ unary-expression
<2> Prefix decrement operator
FUNCTION
The prefix decrement operator decrements the value of an object by 1. The expression “– –E” of the prefix
decrement operator will produce the same result as the following expression:
E = E – 1
or
E –= 1
SYNTAX
–– unary-expression
User’s Manual U14872EJ1V0UM
85
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Address and indirect operators
Unary Operators
& *
<1> Unary & operator
FUNCTION
The unary & operator returns the pointer of a specified object (i.e., the address of the variable it precedes).
SYNTAX
& operand
<2> Unary * operator
FUNCTION
The unary * operator returns the value indicated by a specified pointer (i.e., takes the value of the variable it
precedes and uses that value as the address of the information in memory).
SYNTAX
* operand
NOTE
The operand of the unary & operator must be a left-side value referring to an object not declared with the register
storage class specifier. Neither a function locator nor a bit field can be used as the operand of this unary
operator.
The operand of the unary * operator must have a pointer type.
86
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(3) Unary arithmetic operators (+ – ~ !)
Unary Operators
+ – ~ !
FUNCTIONS
The + (unary plus) operator performs positive integral promotion on its operand.
The – (unary minus) operator performs negative integral promotion on its operand.
The ~ (tilde) operator is a bitwise one’s complement operator which inverts all the bits in a byte of its operand.
The ! NOT or logical negation operator returns 0 if its operand is 0 and 1 if it is not 0. In other words, the
operator changes each 0 to 1 and 1 to 0.
SYNTAX
+ operand
– operand
~ operand
! operand
User’s Manual U14872EJ1V0UM
87
CHAPTER 5
OPERATORS AND EXPRESSIONS
(4) sizeof operator
Unary Operators
sizeof Operator
FUNCTION
The sizeof operator returns the size of a specified object in bytes. The return value is governed by the data type
of the object and the value of the object itself is not evaluated.
The value to be returned by an unsigned char or signed char object (including its qualified type) on which a
sizeof operation is performed is 1. With an array type object, the return value will be the total number of bytes in
the array. With a structure or union type object, the result value will be the total number of bytes that the object
would occupy including bytes necessary to pad out to the next appropriate alignment boundary.
The type of the sizeof operation result is an integral type and its name is size_t. This name is defined in the
<stddef.h> header. The sizeof operator is used mainly to allocate memory areas and transfer data to/from the
I/O system.
SYNTAX
sizeof unary-expression
or
sizeof (type-name)
EXAMPLE
The following example finds the number of elements of an array by dividing the total number of bytes in the array
by the size of a single element. Num becomes 5.
int num;
char array[]= {0, 1, 2, 3, 4};
void func(void){
num = sizeof array / sizeof array [0];
}
NOTE
An expression that has a function type or incomplete type and a left-side value which refers to a bit field object
cannot be used as the operand of this operator.
88
User’s Manual U14872EJ1V0UM
CHAPTER 5
5.4
OPERATORS AND EXPRESSIONS
Cast Operator
A cast is a special operator which forces one data type to be converted into another. The cast operator is mainly
used when converting a pointer type.
Cast Operator
(type-name)
FUNCTION
The cast operator converts the data type of another object (or the result of another expression) into the type
specified in parentheses ( ).
SYNTAX
(type-name) expression
EXAMPLE
void func(void){
int val;
float f;
f=3.14F;
val=(int)f;
/* val becomes 3 by cast */
val=*(int *)0x10000;
/* cast constant */
}
User’s Manual U14872EJ1V0UM
89
CHAPTER 5
5.5
OPERATORS AND EXPRESSIONS
Arithmetic Operators
Arithmetic operators are divided into multiplicative operators and additive operators, in that order of priority.
Multiplicative operators find the product, quotient, and remainder of two operands. Additive operators find the sum
and difference of two operands.
• Multiplicative operators *
/
• Additive operators
–
+
%
Table 5-2. Signs of Division/Remainder Operation Result
b
b
a/b
a%b
+
+
–
+
–
a
–
+
+
+
–
–
–
a
–
Remark
+
–
+
a and b indicate the operands.
Division is performed with two integers whose sign, if any, is removed through the usual arithmetic conversion and
the result will be truncated towards 0 if necessary. Likewise, a remainder or modulo division operation is performed
with two integers whose sign, if any, is removed through the usual arithmetic conversion. Table 5-2 shows the results
of calculations only on the signs of two operands in division and remainder operations, respectively. The following
explain multiplying operators and adding operators. E1 and E2 used in the explanation of syntax indicate operands
or expressions.
90
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Multiplicative operators
Multiplicative Operators
* / %
<1> * operator
FUNCTION
The * operator performs normal multiplication on two operands and returns the product.
SYNTAX
E1 * E2
<2> / operator
FUNCTION
The / operator performs normal division on two operands and returns the quotient.
SYNTAX
E1 / E2
<3> % operator
FUNCTION
The % operator performs a remainder (or modulo division) operation on two operands and returns the remainder
in the result.
SYNTAX
E1 % E2
User’s Manual U14872EJ1V0UM
91
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Additive operators
Additive Operators
+ –
<1> + operator
FUNCTION
The + operator performs addition on two operands and returns the sum of the two numbers.
SYNTAX
E1 + E2
<2> – operator
FUNCTION
The – operator performs subtraction on two operands and returns the difference between the two numbers (the
first operand minus the second operand).
SYNTAX
E1 – E2
92
User’s Manual U14872EJ1V0UM
CHAPTER 5
5.6
OPERATORS AND EXPRESSIONS
Bitwise Shift Operators
A shift operator shifts its first (left) operand in the direction (left or right) indicated by the operator by the number of
bits specified by its second operand. There are the following two shift operators.
• shift operator << >>
Table 5-3. Shift Operations
a<<b
+
bNote
a>>b
0
a
bNote
+
0
–
–1
a
–
0
Note The table indicates when the right operand is greater than the number of bits in the left operand or
when an overflow occurs in the result of the shift operation.
If the right operand is negative, the value is processed as an unsigned positive number.
Remark
a and b indicate the operands.
The shift operators are explained in the following pages. E1 and E2 indicate operands or expressions.
User’s Manual U14872EJ1V0UM
93
CHAPTER 5
OPERATORS AND EXPRESSIONS
Shift Operators
<< >>
<1> Left shift (<<) operator
FUNCTION
The << operator shifts the left operand to the left the number of bits specified by the right operand and fills zeros
in vacated bits. If the left operand E1 has an unsigned type in “E1 << E2”, the result will become a value
obtained by multiplying E1 by the E2th power of 2.
SYNTAX
E1 << E2
<2> Right shift (>>) operator
FUNCTION
The >> operator shifts the left operand to the right the number of bits specified by the right operand. If the left
operand is unsigned, zeros are filled in vacated bits (logical shift). If the left operand is signed, a copy of the
sign bit is filled in vacated bits.
If the left operand E1 is unsigned or signed and has a non-negative value in “E1>>E2”, the result will become a
value obtained by dividing E1 by the E2th power of 2.
SYNTAX
E1 >> E2
94
User’s Manual U14872EJ1V0UM
CHAPTER 5
5.7
OPERATORS AND EXPRESSIONS
Relational Operators
There are two types of operators to indicate the relationship between two operands: “relational operators” and
“equality operators”.
The relational operators indicate the value relationship between two operands such as greater than and less than.
The equality operators indicate that two operands are equal or not equal.
The relational operators and equality operators are shown below.
• Relational operators
<
>
• Equality operators
==
!=
<=
>=
The value relationship between two pointers compared by relational operators is determined by the relative
location in the address space of the object indicated by the pointer.
In this compiler, relational operators and equality operators generate ‘1’ if the specified relationship is true and ‘0’ if
it is false. The results have int type.
The relational operators and equality operators are explained in the following pages. E1 and E2 used in the
explanation of syntax indicate operands or expressions.
User’s Manual U14872EJ1V0UM
95
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Relational operators
Relational Operators
< > <= >=
<1> < (less than) operator
FUNCTION
The < operator returns 1 if the left operand is less than the right operand; otherwise 0 is returned.
SYNTAX
E1 < E2
<2> > (greater than) operator
FUNCTION
The > operator returns 1 if the left operand is greater than the right operand; otherwise 0 is returned.
SYNTAX
E1 > E2
<3> <= (less than or equal) operator
FUNCTION
The <= operator returns 1 if the left operand is less than or equal to the right operand; otherwise 0 is returned.
SYNTAX
E1 <= E2
96
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
Relational Operator
< > <= >=
<4> >= (greater than or equal) operator
FUNCTION
The >= operator returns 1 if the left operand is greater than or equal to the right operand; otherwise 0 is returned.
SYNTAX
E1 >= E2
User’s Manual U14872EJ1V0UM
97
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Equality operators
Equality Operators
= = !=
<1> = = (equal) operator
FUNCTION
The = = operator returns 1 if its two operands are equal to each other; otherwise 0 is returned.
SYNTAX
E1 == E2
<2> != (not equal) operator
FUNCTION
The != operator returns 1 if both operands are not equal to each other; otherwise 0 is returned.
SYNTAX
E1 != E2
98
User’s Manual U14872EJ1V0UM
CHAPTER 5
5.8
OPERATORS AND EXPRESSIONS
Bitwise Logical Operators
Bitwise logical operators perform a specified logical operation on the value of an object in bit units. The bitwise
logical expressions include bitwise AND (&), bitwise exclusive OR ( ^ ), and bitwise inclusive OR ( | ).
Each logical operation is indicated by the operators shown below.
• Betwise AND operator
&
• Bitwise XOR operator
^
• Bitwise OR operator
|
The bitwise logical operators are explained in the following pages. E1 and E2 used in the explanation of syntax
indicate operands or expressions.
User’s Manual U14872EJ1V0UM
99
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Bitwise AND operator
Bitwise AND Operator
&
FUNCTION
The & operator is a bitwise AND operator which returns an integral value that has “1” bits in positions where both
operands have “1” bits and that has “0” bits everywhere else.
The bitwise AND operator must be specified with an “& operator”.
Table 5-4. Bitwise AND Operator
Value of Each Bit in Left Operand
Value of
each bit in
right operand
1
0
1
1
0
0
0
0
SYNTAX
E1 & E2
100
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Bitwise XOR operator
Bitwise XOR Operator
^
FUNCTION
The ^ (caret) operator is a bitwise exclusive OR operator which returns an integral value that has a “1” bit in each
position where exactly one of the operands has a “1” bit and that has a “0” bit in each position where both
operands have a “1” bit or both have a “0” bit.
Table 5-5. Bitwise XOR Operator
Value of Each Bit in Left Operand
Value of
each bit in
right operand
1
0
1
0
1
0
1
0
SYNTAX
E1 ^ E2
User’s Manual U14872EJ1V0UM
101
CHAPTER 5
OPERATORS AND EXPRESSIONS
(3) Bitwise inclusive OR operator
Bitwise Inclusive OR Operator
|
FUNCTION
The | operator is a bitwise inclusive OR operator which returns an integral value that has a “1” bit in each position
where at least one of the operands has a “1” bit and that has a “0” bit in each position where both operands have
a “0” bit.
Table 5-6. Bitwise OR Operator
Value of Each Bit in Left Operand
Value of
each bit in
right operand
1
0
1
1
1
0
1
0
SYNTAX
E1 | E2
102
User’s Manual U14872EJ1V0UM
CHAPTER 5
5.9
OPERATORS AND EXPRESSIONS
Logical Operators
Logical operators perform logical OR and logical AND operations. A logical OR operation is specified with a
logical OR operator, and a logical AND operation is specified with a logical AND operator. Each operator is shown
below.
• Logical AND operator
&&
• Logical OR operator
||
Each operand of both the operators returns the value of int type ‘0’ or ‘1’. The following explains each logical
operator. E1 and E2 used in the explanation of syntax indicate operands or expressions.
User’s Manual U14872EJ1V0UM
103
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Logical AND operator
Logical AND Operator
&&
FUNCTION
The && operator performs a logical AND operation on two operands and returns a “1” if both operands have
nonzero values; otherwise a “0” is returned. The type of the result is int.
Table 5-7. Logical AND Operator
Value of Left Operand
Value of
right operand
Zero
Nonzero
Zero
0
0
Nonzero
0
1
SYNTAX
E1 && E2
NOTE
This operator always evaluates its operands from left to right. If the value of the left operand is “0”, the right
operand is not evaluated.
104
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Logical OR operator
Logical OR Operator
||
FUNCTION
The | | operator performs a logical OR operation on two operands and returns a “0” if both operands are zero;
otherwise a “1” is returned. The type of the result is int.
Table 5-8. Logical OR Operator
Value of Each Bit in Left Operand
Value of
each bit in
right operand
Zero
Nonzero
Zero
0
1
Nonzero
1
1
SYNTAX
E1 || E2
NOTE
This operator always evaluates its operands from left to right. If the value of the left operand is nonzero, the right
operand is not evaluated.
User’s Manual U14872EJ1V0UM
105
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.10 Conditional Operators
Conditional operators judge the processing to be performed next by the value of the first operand. Conditional
operators judge by ‘?’ and ‘:’. The conditional operators are explained below.
Conditional Operators
? :
FUNCTION
If the value of the first operand is nonzero, it evaluates the second operand before the colon. If the value of the
first operand is zero, it evaluates the third operand after the colon. The result of the entire conditional expression
will be the value of the second or third operand.
SYNTAX
1st-operand ? 2nd-operand : 3rd-operand
EXAMPLE
#define TRUE
1
#define FALSE 0
char flag;
int ret;
int func(){
ret=flag ? TRUE : FALSE;
return ret;
}
NOTE
If both the second and third operand types are arithmetic types, normal arithmetic type conversion is performed
to make them common types. The type of result is the common type. If both the operand types are structure
types or union types, the result becomes those types. If both the operand types are void types, the result is
void type.
106
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.11 Assignment Operators
Assignment operators include a simple assignment expression that stores the right operand in the left operand
and a compound assignment expression that stores the result of an operation on both operands in the left operand.
The assignment operators are shown below.
• Assignment Operators
= *= /=
&=
^=
%=
+=
–=
<<=
>>=
|=
The assignment operators are explained in the following pages. E1 and E2 used in the explanation of syntax
indicate operands or expressions.
User’s Manual U14872EJ1V0UM
107
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Simple assignment operator
Simple Assignment Operator
=
FUNCTION
The = operator converts the right operand (expression) to the type of the left operand before the value is stored
in the left object.
In the following example, the value of an int type to be returned from the function by the type conversion of the
simple assignment expression will be converted to a char type and an overflow in the result will be truncated.
The comparison of the value with “–1” will then be made after the value is converted back to the int type. If the
variable “c” declared without a qualifier is not interpreted as unsigned char, the result of the variable will not
become negative and its comparison with “–1” will never result in equal. In such a case, the variable “c” must be
declared with an int type to ensure complete portability.
int f(void);
char c;
/*...*/ ((c=f())==-1) /*...*/
SYNTAX
E1 = E2
108
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Compound assignment operators
Compound Assignment Operators
*= /= %= += –=
<<= >>= &= ^= |=
FUNCTION
The compound assignment operators perform a specified operation on both operands and store the result in the
left object. The value to be stored in the left object will be converted to the type of the left operand. The
compound assignment expression “E1 op = E2” (where op indicates a suitable binary operator) is equivalent to
the simple assignment expression “E1 = E1 op (E2)”, except that the left operand (E1) is only evaluated once.
The following compound assignment expressions will produce the same result as the respective simple
assignment expressions on the right.
a*=b;
a=a*b;
a/=b;
a=a/b;
a%=b;
a=a%b;
a+=b;
a=a+b;
a–=b;
a=a–b;
a<<=b;
a=a<<b;
a>>=b;
a=a>>b;
a&=b;
a=a&b;
a^=b;
a=a^b;
a|=b;
a=a|b;
SYNTAX
E1 *= E2
E1 /= E2
E1 %= E2
E1 += E2
E1 –= E2
E1 <<= E2
E1 >>= E2
E1 &= E2
E1 ^= E2
E1 |= E2
User’s Manual U14872EJ1V0UM
109
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.12 Comma Operator
Comma Operator
,
FUNCTION
The comma operator evaluates the left operand as a void type (that is, ignores its value) and then evaluates the
right operand. The type and value of the result of the comma expression are the type and value of the right
operand.
If a comma has another meaning (as in a list of function arguments or in a list of variable initializations), comma
expressions must be enclosed in parentheses. In other words, the comma operator described in this chapter will
not appear in such a list.
In the following example, the comma operator finds the value of the second argument of the function “f ()”. The
value of the second argument becomes 5.
Int a, c, t;
void main(void) {
f(a,(t=3,t+2),c);
}
SYNTAX
E1 , E2
110
User’s Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.13 Constant Expressions
Constant expressions include general integral constant expressions, arithmetic constant expressions, address
constant expressions, and initialization constant expressions. Most of these constant expressions can be calculated
at translation time instead of execution time.
In a constant expression, the following operators cannot be used except when they appear inside sizeof
expressions.
• Assignment operators
• Increment operators
• Decrement operators
• Function call operator
• Comma operator
(1) General integral constant expression
A general integral constant expression has a general integral type. The following operands may be used.
• Integer constants
• Enumerated value constants
• Character constants
• sizeof expressions
• Floating point constants
(2) Arithmetic constant expression
An arithmetic constant expression has an integral type. The following operands may be used.
• Integer constants
• Enumerated value constants
• Character constants
• sizeof expressions
• Floating point constants
(3) Address constant expression
An address constant expression is a pointer to an object that has a static storage duration or a pointer to a
function locator. Such an expression must be created explicitly using the unary & operator or implicitly using an
expression with an array type or function type. The following operands may be used.
• Array subscript operator [ ]
• . (dot) operator
• −> (arrow) operator
• & address operator
• * indirection operator
• Pointer casts
However, none of these operators can be used to access the value of an object.
User’s Manual U14872EJ1V0UM
111
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
This chapter describes the program control structures of C language and the statements to be executed in C.
Generally speaking, no matter how complicated a process is, it can be expressed with three basic control
structures. These three control structures are: sequential, selection, and iteration. An additional control structure,
branch, is used to change the flow of a program by force.
(1) Sequential processing
Statements in a program are executed one by one from top to bottom in the order of their description in the
program.
(2) Conditional control (selection) processing
According to the status of the program under execution, the next executable statement is selected and executed.
The selection condition is specified in a control statement. The control statement determines which of the two
alternative statement groups or multiway (three or more) alternative statement groups is to be executed.
(3) Looping (iteration) processing
The same processing is executed two or more times. The execution of an executable statement is repeated a
specified number of times while in the state indicated by the control statement.
(4) Branch processing
The current program flow is forcibly interrupted and control is transferred to a specified label. Program execution
starts from the statement next to the specified label.
There are six types of statements used in C.
• Labeled statement...............................
............................................................
and the destination of the goto statement
• Compound statement (block) ..............
Collects two or more statements to be processed as one unit
• Expression statement..........................
A statement consisting of an expression and a semicolon
• Selection statement.............................
Selects a statement out of several statements according to the
............................................................
• Iteration statement ..............................
............................................................
• Branch statement ................................
112
Causes a branch according to the value of the switch statement
value of the expression
Repeatedly performs a statement called the body of a loop until the
control expression becomes equal to 0.
Causes an unconditional branch to different destination
User’s Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
A description example of these statements is shown below.
[Description example]
#define SIZE
10
#define TRUE
1
#define FALSE 0
extern void putchar(char);
extern void lprintf(char *, int);
char
mark [SIZE+1];
void main(void){
int
i, prime, k, count;
count = 0;
for(i = 0 ; i <= SIZE ; i++)
/* for............................
Iteration statement */
/ * for...........................
Iteration statement */
/ * if .............................
Conditional statement */
/ * if .............................
Conditional statement * /
mark [i] = TRUE ;
for(i = 0 ; i <= SIZE ; i++) {
if(mark[i]){
prime = i + i + 3;
lprintf("%d", prime);
if((count%8) == 0)
putchar('\n');
for(k = i + prime ; k <= SIZE ; k += prime)
mark [k] = FALSE;
}
}
lprintf("Total %d\n", count);
loop1;
goto loop1;
/ * loop1: ................................
Labeled statement * /
/ * goto ...................................
Branch statement * /
}
User’s Manual U14872EJ1V0UM
113
CHAPTER 6
6.1
CONTROL STRUCTURES OF C LANGUAGE
Labeled Statements
A labeled statement specifies the destination of a switch or goto statement. The switch statement selects the
statement specified by a control expression from among statements with two or more options. The labeled statement
becomes the label of the statement to be executed by the switch statement.
unconditional branching to the applicable label from the normal flow of processing.
The syntax of labeled statements is given below.
114
User’s Manual U14872EJ1V0UM
The goto statement causes
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) case label
Labeled Statements
case label
FUNCTION
case labels are used only in the body of a switch statement to enumerate values to be taken by the control
expression of the switch statement.
SYNTAX
case constant-expression : statement
EXAMPLE 1
int f(void),i;
void main(void){
/* ... */
switch(f()){
case 1:
i=i+4;
break;
case 2:
i=i+3;
break;
case 3:
i=i+2;
}
/* ... */
}
EXPLANATION
In example 1, if the return value of f( ) is 1, the first case clause (statement) is selected and the expression
“i=i+4” is executed. Likewise, if the return value of f( ) is 2 or 3, the second or third case statement is selected,
respectively. Each break statement in the above example is for exiting the switch statement.
As in this example, case labels are used when two or more options are involved.
User’s Manual U14872EJ1V0UM
115
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
Labeled Statements
case label
EXAMPLE 2
int
i ;
void main (void){
/* ... */
i = 2;
switch(i) {
case 1:
i = i + 4 ;
case 2:
i = i + 3 ;
case 3:
i = i + 2 ;
}
/* ... */
}
EXPLANATION
In example 2, the processing starts in the second case statement since i is 2. The third statement is also
consecutively performed since the case statement does not include a break statement. Thus, if the constant
expression and the control expression in the case statement match, the programs thereafter are performed
sequentially. A break statement is used to exit the switch statement.
116
User’s Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) default label
Labeled Statements
default label
FUNCTION
A default label is a special case label used only in the body of a switch statement to specify a process to be
executed by C if the value of the control expression does not match any of the case constants.
SYNTAX
default: statement
EXAMPLE
int
f (void), i ;
switch (f()) {
case 1:
i = i + 4 ;
break;
case 2:
i = i + 3 ;
break;
case 3:
i = i + 2 ;
default:
i = 1;
}
EXPLANATION
In the above example, if the return value of f( ) is 1, 2, or 3, the corresponding case clause (statement) is
selected and the expression that follows the case label is executed.
Each break statement in the above
example is for exiting the switch statement. If the return value of f( ) is other than 1 to 3, the expression that
follows the default label is executed. In this case, the value of i becomes 1.
User’s Manual U14872EJ1V0UM
117
CHAPTER 6
6.2
CONTROL STRUCTURES OF C LANGUAGE
Compound Statements (Blocks)
A compound statements consist of two or more statements grouped together with enclosing braces and executed
as one unit syntax-wise. In other words, by enclosing zero or more declarations followed by zero or more statements
all in braces, these statements can be processed as a compound statement whenever a single statement is
expected.
6.3
Expression Statements and Null Statements
An expression statement consists of a statement and a semicolon. A null statement consists of only a semicolon
and is used for labels that require a statement and in looping that does not need any body.
The description examples of expression statements and null statements are given below.
As in the following example, for a function to be called as an expression statement merely to obtain side effects,
the value of its return value can be discarded by using a cast expression.
int p(int) ;
void main(void){
/* ... */
(void)p(0) ;
}
A null statement can be used as the body of a looping statement as shown below.
char *s ;
void main(void){
/*...*/
while (*s++ != '0') ;
/*...*/
}
In addition, it can be used to place a label before a brace ( } ) which closes a compound statement as shown
below.
void func(void){
/*...*/
while(loop1){
/*...*/
while(loop2){
/*...*/
if(want_out)
goto end_loop1;
/*...*/
}
end_loop1:;
}
}
118
User’s Manual U14872EJ1V0UM
CHAPTER 6
6.4
CONTROL STRUCTURES OF C LANGUAGE
Selection Statements
Selection statements include if and switch statements. The if or switch statement allows the program to choose
one of several groups of statements to execute, based on the value of the control expression enclosed in
parentheses.
The control flows of the if and switch statements are illustrated in Figure 6-1 below.
Figure 6-1. Control Flows of Selection Statements
Control flow of if statement
if
condition
False
True
Executes
statement
that follows
if.
Executes
statement
that follows
else.
Control flow of switch statement
switch
case 1
case 2
case 3
User’s Manual U14872EJ1V0UM
...
default :
119
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) if and if ... else statements
Selection Statements
if, if ... else
FUNCTION
An if statement executes the statement that follows the control expression enclosed in parentheses if the value
of the control expression is nonzero.
An if ... else statement executes the statement-1 that follows the control expression if the value of the control
expression is nonzero or the statement-2 that follows else if the value of the control expression is zero.
SYNTAX
if (expression) statement
if (expression) statement-1 else statement-2
EXAMPLE
unsigned char
uc;
void func (void){
if( uc < 10 ){
/* 111 */
}
else{
/* 222 */
}
}
EXPLANATION
In the above example, if the value of uc is less than 10 based on the control expression in the if statement, the
block “{/*111*/}” is executed. If the value is greater than 10, the block “{/*222*/}” is executed.
NOTE
When the processing after if statement/if...else statement is not enclosed with “{ }”, only the processing of one
line after the if statement/if...else statement is performed regarding it as the body.
120
User’s Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) switch statement
Selection Statements
switch
FUNCTION
A switch statement has a multiway branching structure and passes control to one of a series of statements that
have the case labels in the switch body depending on the value of the control expression enclosed in
parentheses. If no case label that corresponds to the control expression exists, the statement that follows the
default label is executed. If no default label exists, no statement is executed.
SYNTAX
switch (expression) statement
EXAMPLE
extern void func(void);
unsigned char mode;
void main(void){
switch(mode){
case 2:
mode=8;
break;
case 4:
mode=2;
break;
case 8:
func();
}
}
NOTE
The same value cannot be set in each case label in the switch statement. Only one default label can be used
in the switch statement.
User’s Manual U14872EJ1V0UM
121
CHAPTER 6
6.5
CONTROL STRUCTURES OF C LANGUAGE
Iteration Statements
An iteration statement executes a group of statements in the loop body as long as the value of the control
expression enclosed in parentheses is true (nonzero). C has the following three types of iteration statements.
• while statement
• do statement
• for statement
The control flow of each type of iteration statement is illustrated in Figure 6-2 below.
Figure 6-2. Control Flows of Iteration Statements
Control flow of while loop
Control flow of do-while loop
Control flow of for loop
Loop
Loop
Loop
while
condition
Initialize
False
Executes
statement (s)
that follow
do.
True
Executes
statement (s)
that follow
while.
for
condition
True
True
while
condition
False
Executes
statement (s)
that follow
for.
Reevaluates
control
expression.
122
User’s Manual U14872EJ1V0UM
False
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) while statement
Iteration Statements
while statement
FUNCTION
A while statement executes one or more statements (the body of the while loop) several times as long as the
value of the control expression enclosed in parentheses is true (nonzero). The while statement evaluates the
control expression before executing its loop body.
SYNTAX
while (expression) statements
EXAMPLE
int
i, x ;
void main (void){
i=1,
x=0 ;
while( i < 11 ){
x += i ;
i++ ;
}
}
EXPLANATION
The above example finds the sum total of integers from 1 to 10 for x. The two statements enclosed in braces are
the body of this while loop. The control expression “i<11” returns 0 if the value of i becomes 11. For this
reason, the loop body is executed repeatedly as long as the value of i is less than 11 (between 1 and 10).
“while(1) {statement}” is used to endlessly perform a loop statement.
User’s Manual U14872EJ1V0UM
123
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) do statement
Iteration Statements
do statement
FUNCTION
A do statement executes the body of the loop and then tests the control expression enclosed in parentheses to
see if its value is true (nonzero). The do statement evaluates the control expression after the loop body has
been executed.
SYNTAX
do statements while (expression);
EXAMPLE
int i, x;
void main(void){
i=1,x=0;
do{
x+=i;
i++;
}while(i<11);
}
EXPLANATION
The above example finds the sum total of integers from 1 to 10 for x. The two statements enclosed in braces are
the body of this do ... while loop. The control expression “i<11” returns 0 if the value of i becomes 11. For this
reason, the loop body is executed repeatedly as long as the value of i is less than 11 (between 1 and 10). The
body of the loop is always performed once or more since the control expression of a do statement is evaluated
after execution.
124
User’s Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(3) for statement
Iteration Statements
for statement
FUNCTION
A for statement executes the body of the for loop a specified number of times as long as the value of the control
expression is nonzero (true). Of the three expressions inside the parentheses separated by semicolons, the first
expression is an initializing statement to initialize a variable to be used as a counter and is executed only once in
the beginning of the loop, the second is the control expression for testing the counter value, and the third is a
step statement executed at the end of every loop, after which the variable is reevaluated.
SYNTAX
for(1st-expression ; 2nd-expression ; 3rd-expression) statements
EXAMPLE
int i,x=0;
for(i=1;i<11;++i)
x+=i;
EXPLANATION
The above example finds the sum total of integers from 1 to 10 for x. “x+=i” is the body of this for loop. The
control expression “i<11” returns 0 if the value of i becomes 11. For this reason, the loop body is executed
repeatedly as long as the value of i is less than 11 (between 1 and 10).
NOTE
When the processing after the for statement is not enclosed with “{ }”, only the processing of one line after the
for statements is regarded as the body of the loop of the for statement. The first and the third expression of a
for statement can be omitted. When the second expression is omitted, it is replaced with a constant other than
0. The description of “for (; ;) statement” is used to endlessly perform the body of the loop.
User’s Manual U14872EJ1V0UM
125
CHAPTER 6
6.6
CONTROL STRUCTURES OF C LANGUAGE
Branch Statements
A branch statement is used to exit from the current control flow and transfer control to elsewhere in the program.
Branch statements include the following four statements.
• goto statement
• continue statement
• break statement
• return statement
The control flow of each type of branch statement is shown in Figure 6-3.
Figure 6-3. Control Flows of Branch Statements
continue
Loop
break
Loop
continue
126
User’s Manual U14872EJ1V0UM
break
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) goto statement
Branch Statements
goto
FUNCTION
A goto statement causes program execution to unconditionally jump to the label name specified in the goto
statement within the current function.
SYNTAX
goto identifier ;
EXAMPLE
do{
/*...*/
goto point ;
/*...*/
}while(/*...*/) ;
/*...*/
point: ;
EXPLANATION
In the above example, when control is passed to the goto statement, C unconditionally jumps out of the current
do ... while loop processing and transfers control to the statement next to “point”.
NOTE
The label name (branch destination) to be specified in a goto statement must have been specified within the
current function that includes the goto statement. In other words, a goto can branch only within the current
function - not from one function to another.
User’s Manual U14872EJ1V0UM
127
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) continue statement
Branch Statements
continue
FUNCTION
A continue statement is used in the loop body of an iteration statement. continue ends one cycle of the loop by
transferring control to the end of the loop body. When a continue statement is enclosed by more than one loop,
it ends a cycle of the smallest enclosing loop.
SYNTAX
continue ;
EXAMPLE
while(/*...*/){
/*...*/
continue;
/*...*/
contin:;
}
EXPLANATION
In the above example, when the while loop processing by C reaches the continue statement, C unconditionally
branches to the label “contin”. The label “contin” indicates the branch destination and may be omitted. The
same branching operation may be performed by using “goto contin ;” instead of continue.
NOTE
A continue statement can only be used in the body of loops.
128
User’s Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(3) break statement
Branch Statements
break
FUNCTION
A break statement may appear in the body of an iteration or switch statement and causes control to be
transferred to the statement next to the iteration or switch statement.
SYNTAX
break ;
EXAMPLE
int
i;
unsigned char count, flag;
void main(void){
/*...*/
for(i = 0;i < 20;i++){
switch(count){
case 10:
flag = 1;
break;
/* exit switch statement */
default:
func() ;
}
if (flag)
break;
/*exit for loop */
}
}
EXPLANATION
In the above example, break statements are used so that more than required evaluations are not performed in
the body of the switch statement. If the corresponding case label is found in evaluating the switch statement,
the break statement causes C to exit from the switch statement.
NOTE
A break statement can only be used in the loop or switch body.
User’s Manual U14872EJ1V0UM
129
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(4) return statement
Branch Statements
return
FUNCTION
A return statement exits the function that includes the return and passes controls to the function that called the
return, and calls and returns the value of the return statement expression as the value of the function call
expression. Two or more return statements may be used in a function. Using the closing brace “ } ” at the end
of a function produces the same result as when a return statement without an expression is executed.
SYNTAX
return expression ;
EXAMPLE
int f(int);
void main(void){
/*...*/
int i=0,y=0;
y=f(i);
/*...*/
}
int f(int i){
int x=0;
/*...*/
return(x);
}
EXPLANATION
In the above example, when control is passed to the return statement, the function f() returns a value to the
function main. Because the value of the variable “x” is returned as the return value, the assignment operator
causes the variable “y” to be substituted with the value of the variable “x”.
NOTE
With a void type function, an expression that indicates a return value cannot be used for a return statement.
130
User’s Manual U14872EJ1V0UM
CHAPTER 7
STRUCTURES AND UNIONS
A structure or union is a collection of member objects that have different types and grouped under one given
name. The member objects of a structure are allocated successively to memory space, while the member objects of
a union share the same memory.
User’s Manual U14872EJ1V0UM
131
CHAPTER 7
7.1
STRUCTURES AND UNIONS
Structures
As mentioned earlier, a structure is a collection of member objects successively allocated to memory space.
(1) Declaration of structure and structure variable
A structure declaration list and a structure variable are declared with the keyword struct. Any tag name can be
given to the structure declaration list.
Subsequently, the structure variables of the same structure may be declared using this tag name.
[Declaration of structure]
struct tag name {structure declaration list} variable name;
In the following example, in the first struct declaration, the int type array “code” and char type arrays name,
addr, and tel, with the tag name “data” are specified and no1 is declared as the structure variable. In the
second struct declaration, the structure variables no2, no3, no4, and no5, which have the same structure as
no1 are declared.
[Example]
struct data{
int code;
char name[12];
char addr[50];
char tel[12];
}no1;
struct data no2,no3,no4,no5;
(2) Structure declaration list
The structure declaration list specifies the structure of a structure type to be declared. Individual elements in the
structure declaration list are called members and an area is allocated for each of these members in the order of
their declaration. In the following [Example of structure declaration list], an area is allocated in the order of
variable a, array b, and two-dimensional array c.
Neither an incomplete type (an array of unknown size) nor a function type can be specified as the type of each
member. Therefore, the structure itself cannot be included in the structure declaration list.
Each member can have any object type other than the above two types. A bit field that specifies each member
in bits can also be specified.
If a variable takes a binary value “0” or “1”, the minimum required number of bits is specified as 1 for a bit field.
By this specification of the minimum required number of bits with the bit field, two or more members can be
stored in an integer area.
[Example of structure declaration list]
int a;
char b[7];
char c[5][10];
132
User’s Manual U14872EJ1V0UM
CHAPTER 7
STRUCTURES AND UNIONS
[Example of bit field declaration]
struct bf_tag{
unsigned int a:2;
unsigned int b:3;
bit field
unsigned int c:1;
}bit_field;
(3) Arrays and pointers
Structure variables may also be declared as an array or referenced using a pointer.
[Structure arrays]
An array of structures is declared in the same ways as other objects.
struct data{
char name[12];
char addr[50];
char tel[12];
};
struct data no[5];
[Structure pointers]
A pointer to a structure has the characteristics of the structure indicated by the pointer. In other words, if a
structure pointer is incremented, adding the size of the structure to the pointer points to the next structure.
In the following example, “dt_p” is a pointer to the value of “struct data” type. Here, if the pointer “dt_p” is
incremented, the pointer becomes the same value as “&no[1]”.
struct data no[5];
struct data *dt_p=no;
(4) How to refer to structure members
A structure member (or structure element) may be referenced in two ways: one by using a structure variable and
the other by using a pointer to a variable.
[Reference by using a structure variable]
The . (dot) operator is used for referring to a structure member by using a structure variable.
struct data{
char name[12];
char addr[50];
char tel[12];
}no[5]={"NAME","ADDR","TEL"};*data_ptr=no;
void main(){
char c ;
c=no[0].name[1];
}
User’s Manual U14872EJ1V0UM
133
CHAPTER 7
STRUCTURES AND UNIONS
[Reference by using a pointer to a variable]
The −> (arrow) operator is used for referring to a structure member by using a pointer to a variable.
struct data{
char name[12];
char addr[50];
char tel[12];
}no[5]={"NAME","ADDR","TEL"},*data_ptr=no;
void main(){
char c;
data_ptr->tel[3]='E';
}
7.2
Unions
As mentioned earlier, a union is a collection of members that share the same memory space (or overlap in
memory).
(1) Declaration of union and union variable
A union declaration list and a union variable are declared with the keyword union. Any name called a tag name
can be given to the union declaration list. Subsequently, the union variables of the same union may be declared
using this tag name.
[Declaration of union]
union tag name {union declaration list} variable name;
In the following example, in the first union declaration, char type arrays “name”, “addr”, and “tel” with the tag
name “data” are specified and “no1” is declared as the union variable. In the second union declaration, the
union variables “no2, no3, no4, and no5” which are of the same union as “no1” are declared.
union data{
char name[12];
char addr[50];
char tel[12];
}no1;
union data no2,no3,no4,no5;
(2) Union declaration list
A union declaration list specifies the structure of a union type to be declared. Individual elements in the union
declaration list are called members and an area is allocated for each of these members in the order of their
declaration. In the following [Example of union declaration list], an area is allocated to ‘c’, which becomes the
largest area of the members. The other members are not allocated new areas but use the same area.
Neither an incomplete type (an array of unknown size) nor a function type can be specified as the type of each
member same as the union declaration list.
Each member can have any object type other than the above two types.
134
User’s Manual U14872EJ1V0UM
CHAPTER 7
STRUCTURES AND UNIONS
[Union declaration list]
int a;
char b[7];
char c[5][10];
(3) Union arrays and pointers
Union variables may also be declared as an array or referenced using a pointer (in much the same way as
structure arrays and pointers).
[Union arrays]
An array of unions is declared in the same ways as other objects.
union data{
char name[12];
char addr[50];
char tel[12];
};
union data no[5];
[Union pointers]
A pointer to a union has the characteristics of the union indicated by the pointer. In other words, if a union
pointer is incremented, adding the size of the union to the pointer points to the next union.
In the following example, “dt_p” is a pointer to the value of “union data” type.
union data no[5];
union data *dt_p=no;
(4) How to refer to union members
A union member (or union element) may be referenced in two ways: one by using a union variable and the other
by using a pointer to a variable.
[Reference by using a union variable]
The . (dot) operator is used for referring to a union member by using a union variable.
union data{
char name[12];
char addr[50];
char tel[12];
}no[5]={"NAME","ADDR","TEL"};
void main(void){
no[0].addr[10]='B';
.
.
.
}
User’s Manual U14872EJ1V0UM
135
CHAPTER 7
STRUCTURES AND UNIONS
[Reference by using a pointer to a variable]
The −> (arrow) operator is used for referring to a union member by using a pointer to a variable.
union data{
char name[12];
char addr[50];
char tel[12];
}data_ptr;
void main(void){
data_ptr->name[1]='N';
.
.
.
}
136
User’s Manual U14872EJ1V0UM
CHAPTER 8
EXTERNAL DEFINITIONS
In a program, lists of external declarations come after the preprocessing. These declarations are referred to as
“external declarations” because they appear outside a function and have valid file ranges.
A declaration to give a name to external objects via an identifier or a declaration to secure storage for a function is
called an external definition. If an identifier declared with external linkage is used in an expression (except the
operand part of the sizeof operator), one external definition for the identifier must exist somewhere in the entire
program.
The syntax of external definitions is given below.
#define TRUE
1
#define FALSE 0
#define SIZE
200
void printf(char*,int);
void putchar(char c);
char mark[SIZE+1];
External object definition
main()
{
int i,prime,k,count;
count=0;
for(i=0;i<=SIZE;i++)
mark[i]=TRUE;
for(i=0;i<=SIZE;i++){
if(mark[i]){
prime=i+i+3;
printf("%d",prime);
count++;
if((count%8)==0) putchar('\n');
for(k=i+prime;k<=SIZE;k+=prime)
mark[k]=FALSE;
}
}
printf("Total %d\n",count);
loop1:
goto loop1;
}
User’s Manual U14872EJ1V0UM
137
CHAPTER 8
8.1
EXTERNAL DEFINITIONS
Function Definitions
A function definition is an external definition that begins with a declaration of the function. If the storage class
specifier is omitted from the declaration, extern is assumed to have been defined. An external function definition
means that the defined function may be referenced from other files. For example, in a program consisting of two or
more files, if a function in another file is to be referenced, this function must be defined externally.
The storage class specifier of an external function is extern or static. If a function is declared as extern, the
function can be referenced from another file. If declared as static, it cannot be referenced from another file.
In the following example, the storage class specifier is “extern” and the type specifier is “int”. These two are
default values and thus may be omitted. The function declarator is “max(int a, int b)” and the body of the function is
“{return a>b?a:b;)”.
[Example of function definition]
extern int max(int a, int b)
{
return a > b ? a : b;
}
Because this function definition specifies a parameter type in the function declaration, the type of argument is
forcibly converted by the compiler. This type conversion can be described by using the form of an identifier list for the
parameters. An example of this identifier list is shown below.
extern int max(a, b)
int a, b;
{
return a > b ? a : b;
}
The address of the function may be passed as an argument to a function call. A pointer to the function can be
generated by using the function name in the expression.
int f(void);
void main(){
.
.
.
g(f);
}
138
User’s Manual U14872EJ1V0UM
CHAPTER 8
EXTERNAL DEFINITIONS
In the above example, the function g is passed to the function f by a pointer that points to the function f. The
function g must be defined in either of the following two ways.
void g(int(*funcp)(void))
{
(*funcp)(); /*
or funcp(
);*/
}
or
void g(int func(void))
{
func(); /*
or
(*func) (
);*/
}
User’s Manual U14872EJ1V0UM
139
CHAPTER 8
8.2
EXTERNAL DEFINITIONS
External Object Definitions
An external object definition refers to the declaration of an identifier for an object that has a file scope or initializer.
If the declaration of an identifier for an object which has file scope has no initializer without a storage class
specification or has the storage class static, the object definition is considered to be temporary, because it becomes
a declaration which has file scope with initializer 0.
Examples of external object definitions are shown below.
[Example of external object definition]
140
int i1=1; ..............................
Definition with external linkage
static int i2=2; ...............
Definition with internal linkage
extern int i3=3; ...............
Definition with external linkage
int i4;...................................
Temporary definition with external linkage
static int i5;....................
Temporary definition with internal linkage
int i1;...................................
Valid temporary definition which refers to previous declaration
int i2;...................................
Violation of linkage rule
int i3;...................................
Valid temporary definition which refers to previous declaration
int i4;...................................
Valid temporary definition which refers to previous declaration
int i5;...................................
Violation of linkage rule
extern int i1;....................
Reference to previous declaration which has external linkage
extern int i2;....................
Reference to previous declaration which has internal linkage
extern int i3;....................
Reference to previous declaration which has external linkage
extern int i4;....................
Reference to previous declaration which has external linkage
extern int i5;....................
Reference to previous declaration which has internal linkage
User’s Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
A preprocessing directive is a string of preprocessing tokens between the # preprocessing token and the line feed
character.
White-space characters that can be used between preprocessor token strings are only spaces and horizontal tabs.
A preprocessing directive specifies the processing performed before compiling a source file.
Preprocessing
directives include such operations as processing or skipping a part of a source file depending on the condition,
obtaining additional code from other source files, and replacing the original source code with other text as in macro
expansion. The preprocessing directives are explained in the following pages.
User’s Manual U14872EJ1V0UM
141
CHAPTER 9
9.1
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
Conditional Inclusion
Conditional inclusion skips part of a source file according to the value of a constant expression. If the value of the
constant expression specified by a conditional inclusion directive is 0, the statements that follow the directive are not
translated (compiled). The sizeof operator, cast operator, or an enumerated type constant cannot be used in the
constant expression of any conditional inclusion directive.
Conditional inclusion directives include #if, #elif, #ifdef, #ifndef, #else, and #endif.
In preprocessing directives, the following unary expressions called defined expressions may be used.
defined identifier
defined (identifier)
The unary expressions return 1 if the identifier has been defined with the #define preprocessing directive and 0 if
the identifier has never been defined or its definition has been canceled.
[Example]
In this example, the unary expression returns 1 and compiles between #if and #endif because SYM has been
defined (for the explanation of #if through #endif, refer to the explanations in the following pages).
#define SYM 0
#if defined SYM
.
.
.
#endif
142
User’s Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(1) #if directive
Conditional Inclusion
#if
FUNCTION
The #if directive tells the translation phase of C to skip (discard) a section of source code if the value of the
constant expression is 0.
SYNTAX
#if constant expression new-line group
EXAMPLE
#if FLAG==0
.
.
.
#endif
EXPLANATION
In the above example, the constant expression “FLAG == 0” is evaluated to determine whether a set of
statements (i.e., source code) between #if and #endif is to be used in the translation phase. If the value of
“FLAG” is nonzero, the source code between #if and #endif will be discarded. If the value is zero, the source
code between #if and #endif will be translated.
User’s Manual U14872EJ1V0UM
143
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(2) #elif directive
Conditional Inclusion
#elif
FUNCTION
The #elif directive normally follows the #if directive. If the value of the constant expression of the #if directive is
0, the constant expression of the #elif directive is evaluated. If the constant expression of the #elif directive is 0,
the translation phase of C will skip (discard) the statements (a section of source code) between #elif and #endif.
SYNTAX
#elif constant-expression new-line group
EXAMPLE
#if FLAG==0
.
.
.
#elif FLAG!=0
.
.
.
#endif
EXPLANATION
In the above example, the constant expression “FLAG= =0” or “FLAG!=0” is evaluated to determine whether a
set of statements that follow #if and another set of statements that follow #elif are to be used in the translation
phase. If the value of “FLAG” is zero, the source code between #if and #elif will be translated. If the value is
nonzero, the source code between #elif and #endif will be translated.
144
User’s Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(3) #ifdef directive
Conditional Inclusion
#ifdef
FUNCTION
The #ifdef directive is equivalent to:
#if defined (identifier)
If the identifier has been defined with the #define directive, the statements between #ifdef and #endif will be
translated. If the identifier has never been defined or its definition has been canceled, the translation phase will
skip the source code between #ifdef and #endif.
SYNTAX
#ifdef identifier new-line group
EXAMPLE
#define ON
#ifdef ON
.
.
.
#endif
EXPLANATION
In the above example, the identifier “ON” has been defined with the #define directive. Thus, the source code
between #ifdef and #endif will be translated. If the identifier “ON” has never been defined, the source code
between #ifdef and #endif will be discarded.
User’s Manual U14872EJ1V0UM
145
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(4) #ifndef directive
Conditional Inclusion
#ifndef
FUNCTION
The #ifndef directive is equivalent to:
#if !defined (identifier)
If the identifier has never been defined with the #define directive, the source code between #ifndef and #endif
will not be translated.
SYNTAX
#ifndef identifier new-line group
EXAMPLE
#define ON
#ifndef ON
.
.
.
#endif
EXPLANATION
In the above example, the identifier “ON” has been defined with the #define directive. Thus, the program
between #ifndef and #endif will not be translated. If the identifier “ON” has never been defined, the program
between #ifndef and #endif will be translated.
146
User’s Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(5) #else directive
Conditional Inclusion
#else
FUNCTION
The #else directive tells the translation phase of C to discard a section of source code that follows #else if the
identifier of the preceding conditional inclusion directive is nonzero.
The #if, #elif, #ifdef, or #ifndef directive may precede the #else directive.
SYNTAX
#else new-line group
EXAMPLE
#define ON
#ifdef ON
.
.
.
#else
.
.
.
#endif
EXPLANATION
In the above example, the identifier “ON” has been defined with the #define directive. Thus, the source code
between #ifndef and #endif will be translated. If the identifier “ON” has never been defined, the source code
between #else and #endif will be translated.
User’s Manual U14872EJ1V0UM
147
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(6) #endif directive
Conditional Inclusion
#endif
FUNCTION
The #endif directive indicates the end of a #ifdef block.
SYNTAX
#endif new-line
EXAMPLE
#define ON
#ifdef ON
.
.
.
#endif
EXPLANATION
In the above example, #endif indicates the end of the #ifdef block (effective range of #ifdef directive).
148
User’s Manual U14872EJ1V0UM
CHAPTER 9
9.2
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
Source File Inclusion
The preprocessing directive #include searches for a specified header file and replaces the #include directive with
the entire contents of the header file. The #include directive may take one of the following three forms for inclusion
of other source files.
• #include <file-name>
• #include “file-name”
• #include preprocessing token string
An #include directive may appear in the source obtained by #include. In this compiler, however, there are
restrictions for #include directive nesting.
For the restrictions, refer to Table 1-1 Maximum Performance
Characteristics of This C Compiler.
Remark
Preprocessor token string: Character string defined by the #define directive
User’s Manual U14872EJ1V0UM
149
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(1) #include < > directive
Source File Inclusion
#include< >
FUNCTION
If the directive form is #include < >, the C compiler searches the directory specified by the -i compiler option,
directory specified by the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the
registry for the header file specified in angle brackets and replaces the #include directive line with the entire
contents of the specified file.
SYNTAX
#include <file-name> new-line
EXAMPLE
#include <stdio.h>
EXPLANATION
In the above example, the C compiler searches the directory specified by the INC78K environment variable and
directory \NECTools32\INC78K0S registered in the registry for the file stdio.h and replaces the directive line
#include<stdio.h> with the entire contents of the specified file stdio.h.
Caution The above directories differ depending on the installation method.
150
User’s Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(2) #include “ ” directive
Source File Inclusion
#include “ ”
FUNCTION
If the directive form is #include “ ”, the current working directory is first searched for the header file specified in
double quotes. If it is not found, the directory specified by the -i compiler option, directory specified by the
INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry is searched.
Then, the compiler replaces the #include directive line with the entire contents of the specified file thus
searched.
SYNTAX
#include "file-name" new-line
EXAMPLE
#include "myprog.h"
EXPLANATION
In the above example, the C compiler searches the current working directory, the directory specified by the
INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry for the file
myprog.h specified in double quotes and replaces the directive line #include “myprog.h” with the entire
contents of the specified file myprog.h.
Caution The above directories differ depending on the installation method.
User’s Manual U14872EJ1V0UM
151
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(3) #include preprocessing token string directive
Source File Inclusion
#include token string
FUNCTION
If the directive form is #include preprocessing token string, the header file to be searched is specified by macro
replacement and the #include directive line is replaced by the entire contents of the specified file.
SYNTAX
#include preprocessing token string new-line
EXAMPLE
#define INCFILE "myprog.h"
#define INCFILE
EXPLANATION
In the inclusion of other source files with the directive form #include preprocessing token string, the specified
“preprocessing token string” must be replaced by <file-name> or “file name” using macro replacement. If the
token string is replaced by <file-name>, the C compiler searches the directory specified by the -i compiler option,
directory specified by the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the
registry for the specified file. If the token string is replaced by “file name”, the current working directory is
searched. If the specified file is not found, the directory specified by the -i compiler option, directory specified by
the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry is searched.
152
User’s Manual U14872EJ1V0UM
CHAPTER 9
9.3
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
Macro Replacement
The macro replacement directives #define and #undef are used to replace the character string (macro name)
specified by the identifier with “substitution list”. The #define directive has two forms: object format and function
format:
• Object format
#define identifier replacement-list new-line
• Function format
#define identifier ( identifier-list ) replacement-list new-line
(1) Actual argument replacement
Actual argument replacement is executed after the arguments in the function-form macro call are identified. If
the # or ## preprocessing token is not prefixed to a parameter in the replacement list or if the ## preprocessing
token does not follow any such parameter, all macros in the list will be expanded before replacement with the
corresponding macro arguments.
(2) # operator
The # preprocessing token replaces the corresponding macro argument with a char string processing token. In
other words, if this preprocessing token is prefixed to a parameter in the replacement list, the corresponding
macro argument will be translated into a character or character string.
(3) ## operator
The ## preprocessing token concatenates the two tokens on either side of the ## symbol into one token. This
concatenation will take place before the next macro expansion and the ## preprocessing token will be deleted
after the concatenation. The token generated from this concatenation will undergo macro expansion if it has a
macro name.
[Example of ## operation]
The above macro replacement directive will be expanded as follows.
printf("x""1""=%d,x""2""=%s",x1,x2);
The concatenated char string will look like this.
printf("x1=%d,x2=%s",x1,x2);
#include <stdio.h>
#define
debug(s, t) printf("x"#s"=%d, x"#t"=%s", x##s, x##t);
void main(){
int
x1,
x2;
debug (1, 2);
}
User’s Manual U14872EJ1V0UM
153
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(4) Re-scanning and further replacement
The preprocessing token string resulting from replacement of macro parameters in the list will be scanned again,
together with all remaining preprocessing tokens in the source file. Macro names currently being replaced (not
including the remaining preprocessing tokens in the source file) will not be replaced even if they are found during
scanning of the replacement list.
(5) Scope of macro definition
A macro definition (#define directive) continues macro replacement until it encounters the corresponding #undef
directive.
154
User’s Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(6) #define directive
Macro Replacement
#define
FUNCTION
The #define directive in its simplest form replaces the specified identifier with a given replacement list whenever
the same identifier appears in the source code after the definition by this directive.
SYNTAX
#define identifier replacement-list new-line
EXAMPLE
#define PAI 3.1415
EXPLANATION
In the above example, the identifier “PAI” will be replaced with “3.1415” whenever it appears in the source code
after definition by this directive.
User’s Manual U14872EJ1V0UM
155
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(7) #define ( ) directive
Macro Replacement
#define ( )
FUNCTION
The function-form #define directive replaces the identifier specified in the function format with a given
replacement list whenever the same identifier appears in the source code after definition by this directive.
Function-form macro replacement also includes replacing argument.
SYNTAX
#define identifier ( identifier list ) replacement-list new-line
EXAMPLE
#define F(n) (n*n)
void main(){
int i;
i=F(2)
}
EXPLANATION
In the above example, #define directive will replace “F(2)” with “(2*2)” and thus the value of i will become 4. For
the sake of safety, be sure to enclose the replacement list in parentheses, because unlike a function definition,
this function-form macro merely replaces a sequence of characters.
156
User’s Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(8) #undef directive
Macro Replacement
#undef
FUNCTION
The #undef directive ends the scope of the identifier that has been set by the corresponding #define directive.
SYNTAX
#undef identifier new-line
EXAMPLE
#define F(n) (n*n)
.
.
.
#undef F
EXPLANATION
In the above example, the #undef directive will invalidate the identifier “F” previously specified by “#define F(n)
(n*n)”.
User’s Manual U14872EJ1V0UM
157
CHAPTER 9
9.4
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
Line Control
The preprocessing directive for line control #line replaces the line number to be used by the C compiler in
translation with the number specified by this directive. If a string (character string) is given in addition to the number,
the directive also replaces the source file name the C compiler has with the specified string.
(1) To change the line number
To change the line number, the specification is made as follows. 0 and numbers larger than 32767 cannot be
specified.
#line numeric-string new-line
[Example]
#line 10
(2) To change the line number and the file name
To change the line number and file name, the specification is made as follows.
#line numeric-string "character string" new-line
[Example]
#line 10 "file1.c"
(3) To change using preprocessor token string
In addition to the specifications above, the following specification can also be made. In this case, the specified
preprocessing token string must be either one of the above two examples after all the replacement.
#line preprocessing-token-string new-line
[Example]
#define LINE_NUM 100
#line LINE_NUM
158
User’s Manual U14872EJ1V0UM
CHAPTER 9
9.5
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
#error Preprocessing Directive
The #error preprocessing directive is a directive that outputs a message including the specified preprocessing
tokens and incompletely terminates a compile. This preprocessing is used to terminate a compile.
This preprocessing is specified as follows.
#error "preprocessing-token-string" new-line
[Example]
In this example, the macro name _ _K0S _ _, which indicates the device series that this compiler has, is used. If
the device is the 78K/0S Series, the program between #if and #else is compiled. In the other cases, the
program between #else and #endif is compiled, but the compilation will be terminated with an error message
“not for 78K0S” output by #error directive.
#if _ _K0S_ _
.
.
.
#else
#error "not for 78K0S"
.
.
.
#endif
User’s Manual U14872EJ1V0UM
159
CHAPTER 9
9.6
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
#pragma Directive
The #pragma directive is a directive to instruct the compiler to operate using the compiler definition method. In
this compiler, there are several #pragma directives to generate codes for the 78K/0S Series (For details of the
#pragma directives, refer to CHAPTER 11 EXTENDED FUNCTIONS).
[Example]
In this example, the #pragma NOP directive enables the description to directly output a NOP instruction in the C
source.
#pragma NOP
9.7
Null Directive
Source lines that contain only the # character and white space are called null directives. Null directives are simply
discarded during preprocessing. In other words, these directives have no effect on the compiler. The syntax of null
directives is given below.
# new-line
160
User’s Manual U14872EJ1V0UM
CHAPTER 9
9.8
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
Predefined Macro Names
In this C compiler, the following macro names have been defined.
_ _LINE_ _
Line number of the current source line (decimal constant)
_ _FILE_ _
Source file name (string literal)
_ _DATE_ _
Date the source file was compiled (string literal in the form of “Mmm dd yyyy”)
_ _TIME_ _
Time of day the source file was compiled (string literal in the form of “hh:mm:ss”)
_ _STDC_ _
Decimal constant “1” that indicates the compliance with ANSI
Note
specification
Note ANSI is the acronym for American National Standards Institute
A #define or #undef preprocessing directive must not be applied to these macro names and defined identifiers.
All the macro names of the compiler definition start with an underscore followed by an uppercase character or a
second underscore.
In addition to the above macro names, macro names indicating the series names of devices depending on the
device subject to applied product development and macro names indicating device names are provided. To output
the object code for the target device, these macro names must be specified by the option at compilation time or by
the processor type in the C source.
• Macro name indicating the series names of devices
'_ _K0S_ _'
• Macro name indicating the device name
‘_ _’ is added before the device type name and ‘_’ is added after the device type name.
Describe English characters in uppercase.
(Example) _ _9026_ _ _9216Y_
Remark
The device type names are the same as the ones specified by -C option. For the device type names, refer
to the reference related to device files.
This C compiler has a macro name indicating the memory model.
• Define as follows when the static model is specified
#define _ _STATIC_MODEL_ _ 1
The device type for compilation is specified by adding the following to the command line
‘-c device type name’
(Example)
cc78ks –c9216Y prime.c
User’s Manual U14872EJ1V0UM
161
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
The device type does not need to be specified on compilation by specifying it at the start of the C source program.
‘#pragma PC (device type)’
(Example) #pragma PC(9216Y)
.
.
.
However, the following can be described before ‘#pragma PC (device type)’
• Comment statement
• Preprocessing directives that do not generate a definition/reference of variables nor functions.
162
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
C has no instructions to transfer (input or output) data to and from external sources (peripheral devices and
equipment). This is because of the C language designer's intent to hold the functions of C to a minimum. However,
for actually developing a system, I/O operations are requisite. Thus, C is provided with library functions to perform
I/O operations.
This C compiler is provided with library functions such as I/O, character/memory manipulation, program control,
and mathematical functions. This chapter describes the library functions provided in this compiler.
User’s Manual U14872EJ1V0UM
163
CHAPTER 10
LIBRARY FUNCTIONS
10.1 Interface Between Functions
To use a library function, the function must be called. Calling a library function is carried out by a call instruction.
The arguments and return value of a function are passed by a stack and a register, respectively. However, when the
old function interface supporting option (-ZO) is not specified in the normal model, the first argument is, if possible,
also passed by the register. In addition, all of the arguments are passed by the register in the static model.
For the -ZO option, refer to the CC78K0S C Compiler Operation User’s Manual (U14871E) CHAPTER 5
COMPILER OPTION.
10.1.1 Arguments
Placing or removing arguments on or from the stack is performed by the caller (calling side). The callee (called
side) only references the argument values. However, when the argument is passed by the register, the callee directly
refers to the register and copies the value of the argument to another register, if necessary. Also, when specifying
the function call interface automatic pascal function option -ZR, removal of arguments from the stack is performed by
the called side if the argument is passed on the stack.
Arguments are placed on the stack one by one in descending order from last to top if the argument is passed on
the stack.
The minimum unit of data that can be stacked is 16 bits. A data type larger than 16 bits is stacked in units of 16
bits one by one from its MSB. An 8-bit type data is extended to a 16-bit type data for stacking.
For the static model, all of arguments are passed by a register.
A maximum of 3 arguments and a total of 6 bytes can be passed. Passing float, double, and structure arguments
is not supported.
Lists of argument passing are shown below. The second argument and thereafter is passed via a stack in the
normal model.
The function interface (passing of argument and storing of return value) of the standard library is the same as that
of a normal function.
Table 10-1. List of Passing First Argument (Normal Model)
Type of First Argument
Passing Method
1-byte, 2-byte integers
AX
3-byte integer
AX, BC
4-byte integer
AX, BC
Floating-point number
(float type)
AX, BC
Floating-point number (double type)
AX, BC
Others
Passed via a stack
Remark
164
Of the types shown above, 1- to 4-byte integers include structures and unions.
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
Table 10-2. List of Passing Arguments (Static Model)
Type of Argument
1st Argument
2nd Argument
3rd Argument
1-byte integer
A
B
H
2-byte integer
AX
BC
HL
Remark
If the arguments are a total of 4 bytes, some of the arguments are allocated to AX and BC, and the rest to
HL or H.
1- to 4-byte integers do not include structures and unions.
10.1.2 Return values
The return value of a function is stored in units of 16 bits starting from its LSB in the direction from register BC to
register DE. When returning a structure, the first address of the structure is stored in register BC. When returning a
pointer, the first address of the structure is stored in register BC.
The following shows a list of the storing of the return value. The method of storing return values is the same as
that of normal function.
Table 10-3. List of Storing Return Value
(1) Normal model
Type of Return Value
Method of Storing
1 bit
CY
1-byte, 2-byte integers
BC
4-byte integer
BC (lower), DE (higher)
Floating-point number (float type)
BC (lower), DE (higher)
Floating-point number (double type)
BC (lower), DE (higher)
Structure
Copies the structure to return to the area specific to the
function and stores the address to BC
Pointer
BC
(2) Static model
Type of Return Value
Method of Storing
1 bit
CY
1-byte integer
A
2-byte integer
AX
4-byte integer
AX (lower), BC (higher)
Pointer
AX
10.1.3 Saving registers to be used by individual libraries
Libraries that use HL (normal model) and DE (static model) save the registers used to a stack.
Libraries that use saddr area save the saddr area used to a stack. A stack area is used as a work area for each
library.
User’s Manual U14872EJ1V0UM
165
CHAPTER 10
LIBRARY FUNCTIONS
(1) No -ZR option specified
The procedure of passing arguments and return values is shown below.
Called function "long func(int a, long b, char *c);"
<1> Placing arguments on the stack (by the caller)
The higher 16 bits of arguments “c” and “b” and lower 16 bits of argument “b” are placed on the stack in the
order named. a is passed by the AX register.
<2> Calling func by call instruction (by the caller)
The return address is placed on the stack next to the lower 16 bits of argument “b” and control is
transferred to the function func.
<3> Saving registers to be used within the function (by the callee)
If register HL is to be used, HL is placed on the stack.
<4> Placing the first argument passed by the register on the stack (by the callee)
<5> Processing func and storing the return value in registers (by the callee)
The lower 16 bits of the return value “long” are stored in BC and the higher 16 bits of the return value in
DE.
<6> Restoring the stored first argument (by the callee)
<7> Restoring the saved registers (by the callee)
<8> Returning control to the caller with ret instruction (by the callee)
<9> Removing arguments from the stack (by the caller)
The number of bytes (in units of 2 bytes) of the arguments is added to the stack pointer. In the example
shown in Figure 10-1, 6 is added.
166
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
Figure 10-1. Stack Area When Function Is Called (No -ZR Specified)
Return value in <5> is stored
Lower 16 bits
Higher 16 bits
BC
DE
Stack pointer after <4>
a
Stack pointer after <3>
HL
Stack pointer after <6>
Return address
Stack pointer after <7>
Lower 16 bits of b
Stack pointer after <8>
Stack pointer after <2>
Stack pointer after <1>
Upper 16 bits of b
c
Stack pointer before
stacking arguments
Stack pointer after <9>
High address
(2) -ZR option specified
The following example shows the procedure of passing arguments and return values when the -ZR option is
specified.
Called function "long func(int a, long b, char *c);"
<1> Placing arguments on the stack (by the caller)
The higher 16 bits of arguments “c” and “b” and the lower 16 bits of argument “b” are placed on the stack in
that order. a is passed by the AX register.
Low address
Stack pointer
Lower 16 bits of b
Higher 16 bits of b
c
Stack pointer before
stacking arguments
High address
User’s Manual U14872EJ1V0UM
167
CHAPTER 10
LIBRARY FUNCTIONS
<2> Calling func by a call instruction (by the caller)
Control is transferred to the function func when the stack is in the state shown below.
Low address
Stack pointer
Return
Lower 16 bits of b
Higher 16 bits of b
c
High address
<3> Saving the register used (by the callee)
Low address
Stack pointer
HL
Stack pointer
when called
Return
Lower 16 bits of b
Higher 16 bits of b
c
High address
<4> The first argument called by the register is placed on the stack
Low address
Stack pointer
a
HL
Return
Lower 16 bits of b
Higher 16 bits of b
c
High address
168
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
<5> Performing processing of the function func, and storing return values in the register (by the callee)
The lower 16 bits of the return value are stored in BC and the higher 16 bits are stored in DE.
BC
DE
Lower 16 bits of return value
Higher 16 bits of return value
<6> Restoring the first placed argument (by the callee)
Low address
HL
Stack pointer
Return
Lower 16 bits of b
Higher 16 bits of b
c
High address
<7> Restoring the saved registers (by the callee)
Low address
Return
Stack pointer
Lower 16 bits of b
Higher 16 bits of b
c
High address
<8> Storing the return address in the register and removing the arguments from the stack by shifting the stack
pointer to the position before arguments were placed.
Low address
Stack pointer
Return
Lower 16 bits of b
Higher 16 bits of b
c
High address
User’s Manual U14872EJ1V0UM
169
CHAPTER 10
LIBRARY FUNCTIONS
<9> Restoring the return address stored in the register (by the callee)
Low address
Return
Stack pointer
Stack pointer before
arguments were stacked
High address
<10> Returning control to the functions on the caller by the ret instruction (by the callee)
Low address
Stack pointer before
arguments were stacked
High address
170
User’s Manual U14872EJ1V0UM
Stack pointer
CHAPTER 10
LIBRARY FUNCTIONS
10.2 Headers
This C compiler has 13 headers (or header files). Each header defines or declares standard library functions, data
type names, and macro names.
The headers of this C compiler are as shown below.
ctype.h
setjmp.h
stdarg.h
stdio.h
stdlib.h
string.h
error.h
errno.h
limits.h
stddef.h
math.h
float.h
assert.h
Caution
The functions to be supported differ depending on the memory models (normal model and static
model). Also, functions that operate during normal operation differ depending on the -ZI and -ZL
options. For functions that do not operate normally because of the existence of -ZI and -ZL
options, a warning message “The prototype declaration is not performed” is output.
User’s Manual U14872EJ1V0UM
171
CHAPTER 10
LIBRARY FUNCTIONS
(1) ctype.h
This header is used to define character and string functions. In this standard header, the following library
functions have been defined.
However, when the compiler option -ZA (the option that disables the functions not compliant with ANSI
specifications and enables a part of the functions of ANSI specifications) is specified, _toupper and _tolower
are not defined. Instead, tolow and toup are defined. When -ZA is not specified, tolow and toup are not
defined. The function to be declared differs depending on the options and the specification models.
Table 10-4. Contents of ctype.h
Existence of -ZI, or -ZL
Specification
Normal Model
Static Model
None
ZI
ZL
ZI
ZL
None
ZI
ZL
ZI
ZL
isalnum
√
√
√
√
√
—
√
—
isalpha
√
√
√
√
√
—
√
—
iscntrl
√
√
√
√
√
—
√
—
isdigit
√
√
√
√
√
—
√
—
isgraph
√
√
√
√
√
—
√
—
islower
√
√
√
√
√
—
√
—
isprint
√
√
√
√
√
—
√
—
ispunct
√
√
√
√
√
—
√
—
isspace
√
√
√
√
√
—
√
—
isupper
√
√
√
√
√
—
√
—
isxdigit
√
√
√
√
√
—
√
—
tolower
√
√
√
√
√
—
√
—
toupper
√
√
√
√
√
—
√
—
isascii
√
√
√
√
√
—
√
—
toascii
√
√
√
√
√
—
√
—
_toupper
√
√
√
√
√
—
√
—
_tolower
√
√
√
√
√
—
√
—
tolow
√
√
√
√
√
—
√
—
toup
√
√
√
√
√
—
√
—
Function Name
√: Supported
—: Not supported
172
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(2) setjmp.h
This header is used to define program control functions. In this header, the following functions are defined. The
function to be declared differs depending on the option and the specification models.
Table 10-5. Contents of setjmp.h
Existence of -ZI, or -ZL
Specification
Normal Model
Static Model
None
ZI
ZL
ZI
ZL
None
ZI
ZL
ZI
ZL
setjmp
√
√
√
√
√
—
√
—
longjmp
√
√
√
√
√
—
√
—
Function Name
√: Supported
—: Not supported
In the header setjmp.h, the following object has been defined.
[Declaration of int array type jmp_buf]
• Normal model
typedef int jmp_buf[11];
• Static model
typedef int jmp_buf[3];
User’s Manual U14872EJ1V0UM
173
CHAPTER 10
LIBRARY FUNCTIONS
(3) stdarg.h (normal model only)
This header used to define special functions. In this header, the following three functions have been defined.
Table 10-6. Contents of stdarg.h
Existence of -ZI, or -ZL
Specification
Normal Model
None
ZI
ZL
ZI
ZL
va_arg
√
√
√
√
va_start
∆
∆
∆
∆
va_end
√
√
√
√
Function Name
√: Supported
∆: Operation is guaranteed, however there are limitations
In the header stdarg.h the following object has been declared.
[Declaration of pointer type va_list to char]
typedef char *va_list;
(4) stdio.h
This header is used to define I/O functions. In this header, next functions have been defined.
The function to be declared differs depending on the options and the specification models.
Table 10-7. Contents of stdio.h
Existence of -ZI, or -ZL
Specification
Normal Model
Static Model
None
ZI
ZL
ZI
ZL
None
ZI
ZL
ZI
ZL
sprintf
√
×
√
×
—
—
—
—
sscanf
√
×
√
×
—
—
—
—
printf
√
×
√
×
—
—
—
—
scanf
√
×
√
×
—
—
—
—
vprintf
√
×
√
×
—
—
—
—
vsprintf
√
×
√
×
—
—
—
—
getchar
√
√
√
√
√
—
√
—
gets
√
√
√
√
√
√
√
√
putchar
√
√
√
√
√
—
√
—
puts
√
√
√
√
√
—
√
—
Function Name
√: Supported
×: Operation is not guaranteed
—: Not supported
The following macro names are declared.
#define EOF
(–1)
#define NULL (void *)0
174
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(5) stdlib.h
This header is used to define character and string functions, memory functions, program control functions,
mathematical functions, and special functions. In this standard header, the following library functions have been
defined.
However, when the compiler option -ZA (the option that disables the functions not compliant with ANSI
specifications and enables a part of the functions of ANSI specifications) is specified, brk, sbrk, itoa, ltoa, and
ultoa are not defined.
Instead, strbrk, strsbrk, stritoa, strltoa, and strultoa are defined.
When -ZA is not
specified, these functions are not defined.
Table 10-8. Contents of stdlib.h
Existence of -ZI, or -ZL
Specification
Normal Model
Static Model
None
ZI
ZL
ZI
ZL
atoi
√
×
√
×
√
—
√
—
atol
√
√
×
×
—
—
—
—
strtol
√
√
×
×
—
—
—
—
strtoul
√
√
×
×
—
—
—
—
calloc
√
√
√
√
√
—
√
—
free
√
√
√
√
√
—
√
—
malloc
√
√
√
√
√
—
√
—
realloc
√
√
√
√
√
—
√
—
abort
√
√
√
√
√
√
√
√
atexit
√
√
√
√
√
—
√
—
exit
√
√
√
√
√
—
√
—
abs
√
√
√
√
√
—
√
—
div
√
—
√
—
—
—
—
—
labs
√
√
×
×
—
—
—
—
ldiv
√
√
—
—
—
—
—
—
brk
√
√
√
√
√
—
√
—
sbrk
√
√
√
√
√
—
√
—
atof
√
√
√
√
—
—
—
—
strtod
√
√
√
√
—
—
—
—
itoa
√
√
√
√
√
—
√
—
ltoa
√
√
—
—
—
—
—
—
ultoa
√
√
—
—
—
—
—
—
rand
√
×
√
×
—
—
—
—
srand
√
√
√
√
—
—
—
—
bsearch
√
√
√
√
—
—
—
—
qsort
√
√
√
√
—
—
—
—
strbrk
√
√
√
√
√
—
√
—
strsbrk
√
√
√
√
√
—
√
—
stritoa
√
√
√
√
√
—
√
—
strltoa
√
√
—
—
—
—
—
—
strultoa
√
√
—
—
—
—
—
—
Function Name
None
ZI
ZL
ZI
ZL
√: Supported
×: Operation is not guaranteed
—: Not supported
In the header stdlib.h the following objects have been defined.
User’s Manual U14872EJ1V0UM
175
CHAPTER 10
LIBRARY FUNCTIONS
[Declaration of structure type div_t which has int type members quot and rem (except static model)]
typedef struct{
int quot;
int rem;
}div_t;
[Declaration of structure type ldiv_t which has long int type members quot and rem (except when -ZL is specified in
static model and normal model)]
typedef struct{
long int quot;
long
int
rem;
}ldiv_t;
[Definition of macro name RAND_MAX]
#define RAND_MAX 32767
[Declaration of macro name]
define EXIT_SUCCESS 0
define EXIT_FAILURE 1
176
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(6) string.h
This header is used to define character and string functions, memory functions, and special functions. In this
header, the following functions have been defined. The function to be defined differs depending on the options
and specification models.
Table 10-9. Contents of string.h
Existence of -ZI, or -ZL
Specification
Normal Model
Static Model
None
ZI
ZL
ZI
ZL
None
ZI
ZL
ZI
ZL
memcpy
√
√
√
√
√
—
√
—
memmove
√
√
√
√
√
—
√
—
strcpy
√
√
√
√
√
√
√
√
strncpy
√
√
√
√
√
—
√
—
strcat
√
√
√
√
√
√
√
√
strncat
√
√
√
√
√
—
√
—
memcmp
√
×
√
×
√
—
√
—
strcmp
√
×
√
×
√
—
√
—
strncmp
√
×
√
×
√
—
√
—
memchr
√
√
√
√
√
—
√
—
strchr
√
√
√
√
√
—
√
—
strcspn
√
×
√
×
√
—
√
—
strpbrk
√
√
√
√
√
√
√
√
strrchr
√
√
√
√
√
—
√
—
strspn
√
×
√
×
√
—
√
—
strstr
√
√
√
√
√
√
√
√
strtok
√
√
√
√
√
√
√
√
memset
√
√
√
√
√
—
√
—
strerror
√
√
√
√
√
—
√
—
strlen
√
×
√
×
√
—
√
—
strcoll
√
×
√
×
√
—
√
—
strxfrm
√
×
√
×
√
—
√
—
Function Name
√: Supported
×: Operation is not guaranteed
—: Not supported
User’s Manual U14872EJ1V0UM
177
CHAPTER 10
LIBRARY FUNCTIONS
(7) error.h
error.h includes errno.h.
(8) errno.h
In this header, the following objects have been defined.
[Definitions of macro names “EDOM”, “ERANGE”, and “ENOMEM”]
#define EDOM
1
#define ERANGE 2
#define ENOMEM 3
[Declaration of volatile int type external variable errno]
extern volatile int errno;
(9) limits.h
In this header, the following macro names have been defined.
#define CHAR_BIT
8
#define CHAR_MAX
+127
#define CHAR_MIN
–128
#define INT_MAX
+32767
#define INT_MIN
–32768
#define LONG_MAX
+2147483647
#define LONG_MIN
–2147483648
#define SCHAR_MAX
+127
#define SCHAR_MIN
–128
#define SHRT_MAX
+32767
#define SHRT_MIN
–32768
#define UCHAR_MAX
255U
#define UINT_MAX
65535U
#define ULONG_MAX
4294967295U
#define USHRT_MAX
65535U
#define SINT_MAX
+32767
#define SINT_MIN
–32768
#define SSHRT_MAX
+32767
#define SSHRT_MIN
–32768
However, when the -QU option, which regards unqualified char as unsigned char, is specified, CHAR_MAX
and CHAR_MIN are declared as follows, via the macro _ _CHAR_UNSIGNED_ _ declared by the compiler.
178
#define CHAR_MAX
(255U)
#define CHAR_MIN
(0)
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
When the -ZI option (int and short types are regarded as char type, unsigned int and unsigned short as
unsigned char) is specified as a compiler option, INT_MAX, INT_MIN, SHRT_MAX, SHRT_MIN, SINT_MAX,
SINT_MIN, SSHRT_MAX, SSHRT_MIN, UINT_MAX, and USHRT_MAX are declared as follows, via the macro
_ _FROM_INT_TO_CHAR_ _ declared by the compiler.
#define INT_MAX
CHAR_MAX
#define INT_MIN
CHAR_MIN
#define SHRT_MAX
CHAR_MAX
#define SHRT_MIN
CHAR_MIN
#define SINT_MAX
SCHAR_MAX
#define SINT_MIN
SCHAR_MIN
#define SSHRT_MAX
SCHAR_MAX
#define SSHRT_MIN
SCHAR_MIN
#define UINT_MAX
UCHAR_MAX
#define USHRT_MAX
UCHAR_MIN
When the -ZL option (long type is regarded as int type and unsigned long as unsigned int) is specified as a
compiler option, LONG_MAX, LONG_MIN, and ULONG_MAX are declared as follows, via the macro
_ _FROM_LONG_TO_INT_ _ declared by the compiler.
#define LONG_MAX
(+32767)
#define LONG_MIN
(-32768)
#define ULONG_MAX
(65535U)
User’s Manual U14872EJ1V0UM
179
CHAPTER 10
LIBRARY FUNCTIONS
(10) stddef.h
In this header, the following objects have been declared and defined.
[Declaration of int type ptrdiff_t]
typedef int ptrdiff_t;
[Declaration of unsigned int type size_t]
typedef unsigned int size_t;
[Definition of macro name NULL]
#define NULL (void*)0;
[Definition of macro name offsetof]
#define offsetof(type, member) ((size_t)&(((type*)0)->member))
• offsetof (type, member specifier)
offsetof is expanded to the general integer constant expression that has type size_t and the value is an
offset value in byte units from the start of the structure (that is specified by the type) to the structure member
(that is specified by the member specifier).
The member specifier must be the one that the result of evaluation of the expression & (t. member specifier)
becomes an address constant when static type t; is declared. When the specified member is a bit field, the
operation will not be guaranteed.
180
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(11) math.h (normal model only)
math.h defines the following functions.
Table 10-10. Contents of math.h (1/2)
Existence of -ZI, or -ZL
Specification
Normal Model
None
ZI
ZL
ZI
ZL
acos
√
√
√
√
asin
√
√
√
√
atan
√
√
√
√
atan2
√
√
√
√
cos
√
√
√
√
sin
√
√
√
√
tan
√
√
√
√
cosh
√
√
√
√
sinh
√
√
√
√
tanh
√
√
√
√
exp
√
√
√
√
frexp
√
√
√
√
ldexp
√
√
√
√
log
√
√
√
√
log10
√
√
√
√
modf
√
√
√
√
pow
√
√
√
√
sqrt
√
√
√
√
ceil
√
√
√
√
fabs
√
√
√
√
floor
√
√
√
√
fmod
√
√
√
√
matherr
√
—
√
—
acosf
√
√
√
√
asinf
√
√
√
√
atanf
√
√
√
√
atan2f
√
√
√
√
cosf
√
√
√
√
sinf
√
√
√
√
tanf
√
√
√
√
coshf
√
√
√
√
sinhf
√
√
√
√
tanhf
√
√
√
√
expf
√
√
√
√
frexpf
√
√
√
√
ldexpf
√
√
√
√
logf
√
√
√
√
log10f
√
√
√
√
modff
√
√
√
√
Function Name
√: Supported
—: Not supported
User’s Manual U14872EJ1V0UM
181
CHAPTER 10
LIBRARY FUNCTIONS
Table 10-10. Contents of math.h (2/2)
Existence of -ZI, or -ZL
Specification
Normal Model
None
ZI
ZL
ZI
ZL
powf
√
√
√
√
sqrtf
√
√
√
√
ceilf
√
√
√
√
fabsf
√
√
√
√
floorf
√
√
√
√
fmodf
√
√
√
√
Function Name
√: Supported
The following objects are defined.
[Definition of macro name HUGE_VAL]
#define HUGE_VAL DBL_MAX
182
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(12) float.h
float.h defines the following objects.
When the size of a double type is 32 bits, the macros to be defined are sorted by the macro
_ _DOUBLE_IS_32BITS_ _ declared by the compiler.
#ifndef _FLOAT_H
#define FLT_ROUNDS
1
#define FLT_RADIX
2
#ifdef _ _DOUBLE_IS_32BITS_ _
#define FLT_MANT_DIG
24
#define DBL_MANT_DIG
24
#define LDBL_MANT_DIG
24
#define FLT_DIG
6
#define DBL_DIG
6
#define LDBL_DIG
6
#define FLT_MIN_EXP
–125
#define DBL_MIN_EXP
–125
#define LDBL_MIN_EXP
–125
#define FLT_MIN_10_EXP
–37
#define DBL_MIN_10_EXP
–37
#define LDBL_MIN_10_EXP
–37
#define FLT_MAX_EXP
+128
#define DBL_MAX_EXP
+128
#define LDBL_MAX_EXP
+128
#define FLT_MAX_10_EXP
+38
#define DBL_MAX_10_EXP
+38
#define LDBL_MAX_10_EXP
+38
#define FLT_MAX
3.40282347E+38F
#define DBL_MAX
3.40282347E+38F
#define LDBL_MAX
3.40282347E+38F
#define FLT_EPSILON
1.19209290E–07F
#define DBL_EPSILON
1.19209290E–07F
#define LDBL_EPSILON
1.19209290E–07F
#define FLT_MIN
1.1749435E–38F
#define DBL_MIN
1.17549435E–38F
#define LDBL_MIN
1.17549435E–38F
User’s Manual U14872EJ1V0UM
183
CHAPTER 10
#else
/* _ _DOUBLE_IS_32BITS_ _ */
#define FLT_MANT_DIG
24
#define DBL_MANT_DIG
53
#define LDBL_MANT_DIG
53
#define FLT_DIG
6
#define DBL_DIG
15
#define LDBL_DIG
15
#define FLT_MIN_EXP
–125
#define DBL_MIN_EXP
–1021
#define LDBL_MIN_EXP
–1021
#define FLT_MIN_10_EXP
–37
#define DBL_MIN_10_EXP
–307
#define LDBL_MIN_10_EXP
–307
#define FLT_MAX_EXP
+128
#define DBL_MAX_EXP
+1024
#define LDBL_MAX_EXP
+1024
#define FLT_MAX_10_EXP
+38
#define DBL_MAX_10_EXP
+308
#define LDBL_MAX_10_EXP
+308
#define FLT_MAX
3.40282347E+38F
#define DBL_MAX
1.7976931348623157E+308
#define LDBL_MAX
1.7976931348623157E+308
#define FLT_EPSILON
1.19209290E-07F
#define DBL_EPSILON
2.2204460492503131E-016
#define LDBL_EPSILON
2.2204460492503131E-016
#define FLT_MIN
1.17549435E-38F
#define DBL_MIN
2.225073858507201E-308
#define LDBL_MIN
2.225073858507201E-308
#endif
184
LIBRARY FUNCTIONS
/* _ _DOUBLE_IS_32BITS_ _ */
#define
_FLOAT_H
#endif
/* !_FLOAT_H */
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(13) assert.h (normal model only)
Table 10-11. Contents of assert.h
Existence of -ZI, or -ZL
Specification
Normal Model
None
ZI
ZL
ZI
ZL
√
√
√
√
Function Name
_ _assertfail
√: Supported
assert.h defines the following objects.
#ifdef NDEBUG
#define assert(p) ((void)0)
#else
extern int _ _assertfail(char*_ _msg, char*_ _cond, char*_ _file, int_ _line);
#define assert(p) ((p) ? (void)0 : (void)_ _assertfail( \
"Assertion failed:
%s, file %s, line %d\n", #p, _ _FILE_ _, _ _LINE_ _))
#endif /* NDEBUG */
However, if the assert.h header file references another macro, NDEBUG, which is not defined by the assert.h
header file, and if NDEBUG is defined as a macro when the assert.h is captured to the source file, the assert.h
header file simply declares the assert macro as:
#define assert(p) ((void)0)
and does not define _ _ assertfail.
10.3 Re-entrantability (Normal Model Only)
Re-entrant is a state where a function called from a program can be consecutively called from another program.
The standard library of this compiler does not use static area allowing re-entrantability. Therefore, data in the
storage area used by functions will not be destroyed by a call from another program.
However, the functions shown in (1) to (3) are not re-entrant.
(1) Functions that cannot be re-entranced
setjmp, longjmp, atexit, exit
(2) Functions that use the area secured in the startup routine
div, ldiv, brk, sbrk, rand, srand, strtok
(3) Functions that deal with floating-point numbers
sprintf, sscanf, printf, scanf, vprintf, vsprintf
Note
, atof, strtod, all the mathematical functions
Note Among sprintf, sscanf, printf, scanf, vprintf, and vsprintf, functions that do not support floating-point
numbers are re-entrant.
User’s Manual U14872EJ1V0UM
185
CHAPTER 10
LIBRARY FUNCTIONS
10.4 Standard Library Functions
This section explains the standard library functions of this C compiler classified by function as follows. All standard
library functions are supported even when the -ZF option is specified.
• Item (1-x)
Character and character string functions
• Item (2-x)
Program control functions
• Item (3-x)
Special functions
• Item (4-x)
I/O functions
• Item (5-x)
Utility functions
• Item (6-x)
Character string/memory functions
• Item (7-x)
Mathematical functions
• Item (8-x)
Diagnostic functions
186
User’s Manual U14872EJ1V0UM
CHAPTER 10
1-1
LIBRARY FUNCTIONS
is-
Character & String Functions
FUNCTION
is- judges the type of character.
HEADER
ctype.h for all the character functions
FUNCTION PROTOTYPE
int is-(int c);
Function
is-
Arguments
Return Value
c.. Character to be judged
1 if character c is included in
the character range.
0 if character c is not included
in the character range.
EXPLANATION
Function
Character Range
isalpha
Alphabetic character A to Z or a to z
isupper
Uppercase letters A to Z
islower
Lowercase letters a to z
isdigit
Numeric characters 0 to 9
isalnum
Alphanumeric characters 0 to 9 and A to Z or a to z
isxdigit
Hexadecimal numbers 0 to 9 and A to F or a to f
isspace
White-space characters (space, tab, carriage return, new-line,
vertical tab, and form-feed)
ispunct
Punctuation characters except white-space characters
isprint
Printable characters
isgraph
Printable nonblank characters
iscntrl
Control characters
isascii
ASCII character set
User’s Manual U14872EJ1V0UM
187
CHAPTER 10
1-2
LIBRARY FUNCTIONS
toupper
tolower
Character & String Functions
FUNCTION
The character functions toupper and tolower both convert one type of character to another.
The toupper function returns the uppercase equivalent of c if c is a lowercase letter.
The tolower function returns the lowercase equivalent of c if c is a uppercase letter.
HEADER
ctype.h
FUNCTION PROTOTYPE
int to-(int c);
Function
toupper, tolower
Arguments
c.. Character to be converted
Return Value
Uppercase equivalent if c is a
convertible character.
Character “c” is returned
unchanged if not convertible.
EXPLANATION
toupper
• The toupper function checks to see if the argument is a lowercase letter and if so converts the letter to its
uppercase equivalent.
tolower
• The tolower function checks to see if the argument is a uppercase letter and if so converts the letter to its
lowercase equivalent.
188
User’s Manual U14872EJ1V0UM
CHAPTER 10
1-3
LIBRARY FUNCTIONS
toascii
Character & String Functions
FUNCTION
The character function toascii converts “c” to an ASCII code.
HEADER
ctype.h
FUNCTION PROTOTYPE
int toascii(int c);
Function
toascii
Arguments
c.. Character to be converted
Return Value
Value obtained by converting
the bits outside the ASCII
code range of “c” to 0.
EXPLANATION
The toascii function converts the bits (bits 7 to 15) of “c” outside the ASCII code range of “c” (bits 0 to 6) to “0”
and returns the converted bit value.
User’s Manual U14872EJ1V0UM
189
CHAPTER 10
1-4
LIBRARY FUNCTIONS
_toupper/toup
_tolower/tolow
Character & String Functions
FUNCTION
The character function _toupper/toup subtracts “a” from “c” and adds “A” to the result.
The character function _tolower/tolow subtracts “A” from “c” and adds “a” to the result.
(_toupper is exactly the same as toup, and _tolower is exactly the same as the tolow)
Remark
a: Lowercase; A: Uppercase
HEADER
ctype.h
FUNCTION PROTOTYPE
int _to-(int c);
Function
_toupper
toup
Arguments
c.. Character to be converted
_tolower
tolow
Remark
Return Value
Value obtained by adding “A”
to the result of subtracting “a”
from “c”
Value obtained by adding “a”
to the result of subtracting “A”
from “c”
a: Lowercase; A: Uppercase
EXPLANATION
_toupper
• The _toupper function is similar to toupper except that it does not test to see if the argument is a lowercase
letter.
_tolower
• The _tolower function is similar to tolower, except it does not test to see if the argument is an uppercase
letter.
190
User’s Manual U14872EJ1V0UM
CHAPTER 10
2-1
LIBRARY FUNCTIONS
setjmp
longjmp
Program Control Functions
FUNCTION
The program control function setjmp saves the environment information (current state of the program) when a
call to this function is made.
The program control function longjmp restores the environment information saved by setjmp.
HEADER
setjmp. h
FUNCTION PROTOTYPE
int setjmp(jmp_buf env);
void longjmp(jmp_buf env,int val);
Function
setjmp
Arguments
env ... Array to which
environment information is to
be saved
Return Value
• 0 if called directly
• Value given by “val” if
returning from the
corresponding longjmp or 1
if “val “ is 0
longjmp
env ... Array to which
longjmp will not return
environment information was
saved by setjmp
val ... Return value to setjmp
because program execution
resumes at statement next to
setjmp that saved
environment to “env”.
EXPLANATION
setjmp
• setjmp, when called directly, saves the saddr area, SP, and the return address of the function, which are
used as the HL register or register variables, to env and returns 0.
longjmp
• The longjmp restores the saved environment to env (saddr area and SP used as HL register or register
variables). Program execution continues as if the corresponding setjmp returns val (however, if val is 0, 1 is
returned).
User’s Manual U14872EJ1V0UM
191
CHAPTER 10
3-1
LIBRARY FUNCTIONS
va_start (normal model only)
va_arg (normal model only)
va_end (normal model only)
Special Functions
FUNCTION
The va_start function (macro) is used to start a variable argument list.
The va_arg function (macro) obtains the value of an argument from a variable argument list.
The va_end function (macro) indicates that the end of a variable argument list is reached.
HEADER
stdarg. h
FUNCTION PROTOTYPE
void va_start(va_list ap,parmN);
type va_arg(va_list ap,type);
void va_end(va_list ap);
Function
va_start
Arguments
ap ... Variable to be
Return Value
None
initialized so as to be used in
va_arg and va_end
parmN ... The argument
before variable argument
va_arg
ap ... Variable to process
an argument list
type... Type to point the
relevant place of variable
argument (type is a type of
Normal case ... Value in the
relevant place of variable
argument
If ap is a null pointer ... 0
variable length; for example,
int type if described as va_arg
(va_list ap, int) or long type if
described as va_arg (va_list
ap, long))
va_end
ap .... Variable to process the
None
variable number of arguments
192
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
va_start (normal model only)
va_arg (normal model only)
va_end (normal model only)
Special Functions
EXPLANATION
va_start
• In the va_start macro, the argument ap must be a va_list type (char* type) object.
• A pointer to the next argument of parmN is stored in ap.
• parmN is the name of the last (right-most) parameter specified in the function's prototype.
• If parmN has the register storage class, proper operation of this function is not guaranteed.
va_arg
• In the va_arg macro, the argument ap must be the same as the va_list type object initialized with va_start
(otherwise normal operation is not guaranteed).
• va_arg returns a value in the relevant place of variable arguments as a type of type.
The relevant place is the first variable argument immediately after va_start and each va_arg following that.
• If the argument pointer ap is a null pointer, va_arg returns 0 (of type type).
va_end
• The va_end macro sets a null pointer in the argument pointer ap to inform the macro processor that all the
parameters in the variable argument list have been processed.
User’s Manual U14872EJ1V0UM
193
CHAPTER 10
4-1
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
FUNCTION
The sprintf function writes data into a character string (array) according to the format.
HEADER
stdio.h
FUNCTION PROTOTYPE
int sprintf(char *s,const char *format,...);
Function
sprintf
Arguments
Return Value
s ... Pointer to the string into
which the output is to be
written
format ... Pointer to the string
which indicates format
commands
... ... Zero or more arguments
to be converted
Number of characters written
in s (terminating null character
is not counted.)
EXPLANATION
• If there are fewer actual arguments than formats, operation is not guaranteed. If formats run out with actual
arguments still remaining, the excess actual arguments are just evaluated and ignored.
• sprintf converts zero or more arguments that follow format according to the format command specified by
format and writes (copies) them into the string s.
• Zero or more format commands may be used. Ordinary characters (other than format commands that begin
with a % character) are output as is to the string s. Each format command takes zero or more arguments that
follow format and outputs them to the string s.
• Each format command begins with a % character and is followed by these:
• Zero or more flags (to be explained later) that modify the meaning of the format command
• Optional decimal integer which specify a minimum field width
If the output width after the conversion is less than this minimum field width, this specifier pads the output with
blanks of zeros on its left. (If the left-justifying flag “-” (minus) sign follows %, zeros are padded out to the right
of the output.)
The default padding is done with spaces. If the output is to be padded with 0s, place a 0 before the field width
specifier. If the number or string is greater than the minimum field width, it will still be printed in full and not
truncated.
194
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
• Optional precision (number of decimal places) specification (. integer)
With d, i, o, u, x, and X type specifiers, the minimum number of digits is specified. With the s type specifier,
the maximum number of characters (maximum field width) is specified. The number of digits to be output
following the decimal point is specified for e, E, and f conversions. The number of maximum valid digits is
specified for g and G conversions. This precision specification must be made in the form of (.integers). If the
integer part is omitted, 0 is assumed to have been specified. The amount of padding resulting from this
precision specification takes precedence over the padding by the field width specification.
• Optional h, l and L modifiers
The h modifier instructs the sprintf function to perform the d, i, o, u, x, or X type conversion that follows this
modifier on short int or unsigned short int type. The h modifier instructs the sprintf function to perform the n
type conversion that follows this modifier on a pointer to short int type.
The l modifier instructs the sprintf function to perform the d, i, o, u, x, or X type conversion that follows this
modifier on long int or unsigned long int type. The h modifier instructs the sprintf function to perform the n
type conversion that follows this modifier on a pointer to long int type.
For other type specifiers, the h, l or L modifier is ignored.
• Character that specifies the conversion (to be explained later)
In the minimum field width or precision (number of decimal places) specification, * may be used in place of an
integer string. In this case, the integer value will be given by the int argument (before the argument to be
converted). Any negative field width resulting from this will be interpreted as a positive field that follows the (minus) flag. All negative precision will be ignored.
The following flags are used to modify a format command:
– ................... The result of a conversion is left-justified within the field.
+................... The result of a signed conversion always begins with a + or - sign.
Space........... If the result of a signed conversion has no sign, a space is prefixed to the output. If the +
(plus) flag and space flag are specified at the same time, the space flag will be ignored.
# ................... The result is converted in the assignment form.
In the o type conversion, precision is increased so that the first digit becomes 0. In the x or X
type conversion, 0x or 0X is prefixed to a nonzero result. In the e, E, and f type conversions, a
decimal point is forcibly inserted to all the output values (in the default without #, a decimal
point is displayed only when there is a value to follow).
In the g and G type conversions, a decimal point is forcibly inserted in all the output values,
and truncation of 0 to follow will not be allowed (in the default without #, a decimal point is
displayed only when there is a value to follow. The 0 to follow will be truncated). In all the
other conversions, the # flag is ignored.
User’s Manual U14872EJ1V0UM
195
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
The format codes for output conversion specifications are as follows,
d ................... Converts int argument to signed decimal format.
i .................... Converts int argument to signed decimal format.
o ................... Converts int argument to unsigned octal format.
u ................... Converts int argument to unsigned decimal format.
x ................... Converts int argument to unsigned hexadecimal format (with lowercase letters abcdef).
X................... Converts int argument to unsigned hexadecimal format (with uppercase letters ABCDEF).
With d, i, o, u, x and X type specifiers, the minimum number of digits (minimum field width) of the result is
specified. If the output is shorter than the minimum field width, it is padded with zeros. If no precision is
specified, 1 is assumed to have been specified. Nothing will appear if 0 is converted with 0 precision.
f .................... Converts double argument as a signed value with [-] dddd.dddd format.
dddd is one or more decimal number(s). The number of digits before the decimal point is
determined by the absolute value of the number, and the number of digits after the decimal
point is determined by the required precision. When the precision is omitted, it is interpreted
as 6.
e ................... Converts double argument as a signed value with [-] d.dddd e [sign] ddd format. d is one
decimal number, and dddd is one or more decimal number(s). ddd is exactly a three-digit
decimal number, and the sign is + or –. When the precision is omitted, it is interpreted as 6
E................... The same format as that of e except E is added instead of e before the exponent.
g ................... Uses whichever shorter method of f or e format when converting double argument based on
the specified precision. e format is used only when the exponent of the value is smaller than –
4 or larger than the specified number by precision.
The following 0s are truncated, and the decimal point is displayed only when one or more
numbers follow.
G .................. The same format as that of g except E is added instead of e before the exponent.
c ................... Converts int argument to unsigned char and writes the result as a single character.
s ................... The associated argument is a pointer to a string of characters and the characters in the string
are written up to the terminating null character (but not included in the output). If precision is
specified, the characters exceeding the maximum field width will be truncated off the end.
When the precision is not specified or larger than the array, the array must include a null
character.
p ................... The associated argument is a pointer to void and the pointer value is displayed in
hexadecimal 4 digits (with 0s prefixed to less than a 4-digit pointer value). The precision
specification if any will be ignored.
n ................... The associated argument is an integer pointer into which the number of characters written
thus far in the string “s” is placed. No conversion is performed.
% .................. Prints a % sign. The associated argument is not converted (but the flag and minimum field
width specifications are valid).
196
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
• Operations for invalid conversion specifiers are not guaranteed.
• When the actual argument is a union or a structure, or the pointer to indicate them (except the character type
array in % s conversion or the pointer in % p conversion), operations are not guaranteed.
• The conversion result will not be truncated even when there is no field width or the field width is small. In
other words, when the number of characters of the conversion result are larger than the field width, the field is
extended to the width that includes the conversion result.
• The formats of the special output character string in %f, %e, %E, %g, %G conversions are shown below.
non-numeric
→ “(NaN)”
+∞
→ “(+INF)”
–∞
→“(–INF)”
sprintf writes a null character at the end of the string s. (This character is included in the return value count.)
The syntax of format commands is illustrated in Figure 10-2.
User’s Manual U14872EJ1V0UM
197
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
Figure 10-2. Syntax of Format Commands
format:
Format command
Ordinary char.
Ordinary
characters:
Format command:
Characters except %
%
Flags
Min. field width
Precision
h
I
L
Flags:
–
Format codes:
d
+
i
Space
o
#
u
x
X
Minimum field width:
Digits
c
*
s
Precision:
.
p
Digits
n
*
f
e
E
g
G
%
198
User’s Manual U14872EJ1V0UM
Format code
CHAPTER 10
4-2
LIBRARY FUNCTIONS
sscanf (normal model only)
I/O Functions
FUNCTION
The sscanf function reads data from the input string (array) according to the format.
HEADER
stdio.h
FUNCTION PROTOTYPE
int sscanf(const char *s,const char *format,...);
Function
sscanf
Arguments
Return Value
s ... Pointer to the input string
format ... Pointer to the string
which indicates the input
format commands
... ... Pointer to object in which
converted values are to be
stored, and zero or more
arguments
–1 if the string s is empty.
Number of assigned input data
items if the string s is not
empty.
EXPLANATION
• sscanf inputs data from the string pointed to by s. The string pointed to by format specifies the input string
allowed for input. Zero or more arguments after format are used as pointers to an object. format specifies
how data is to be converted from the input string.
• If there are insufficient arguments to match the format commands pointed to by format, proper operation by
the compiler is not guaranteed.
For excessive arguments, expression evaluation will be performed but no data will be input.
• The control string pointed to by format consists of zero or more format commands which are classified into
the following three types.
(a) White-space characters (one or more characters for which isspace becomes true)
(b) Non-white-space characters (other than %)
(c) Format specifiers
• Each format specifier begins with the % character and is followed by these:
• Optional * character which suppresses assignment of data to the corresponding argument
• Optional decimal integer which specifies a maximum field width
• Optional h, l or L modifier which indicates the object size on the receiving side
If h precedes the d, i, o, or x format specifier, the argument is a pointer to not int but short int.
If l precedes any of these format specifiers, the argument is a pointer to long int.
Likewise, if h precedes the u format specifier, the argument is a pointer to unsigned short int.
If l precedes the u format specifier, the argument is a pointer to unsigned long int.
If l precedes the conversion specifier e, E, f, g, G, the argument is a pointer to double (a pointer to float in
default without l). If L precedes, it is ignored.
Remark
Conversion specifier: Character to indicate the type of corresponding conversion (to be described
later)
User’s Manual U14872EJ1V0UM
199
CHAPTER 10
LIBRARY FUNCTIONS
sscanf (normal model only)
I/O Functions
sscanf executes the format commands in “format” in sequence and if any format command fails, the function will
terminate.
(a) A white-space character in the control string causes sscanf to read any number (including zero) of whitespace characters up to the first non-white-space character (which will not be read). This white-space
character command fails if it does not encounter any non-white-space characters.
(b) A non-white-space character causes sscanf to read and discard a matching character. This command
fails if the specified character is not found.
(c) The format commands define a collection of input streams for each type specifier (to be described later).
The format commands are executed according to the following steps.
• The input white-space characters (specified by isspace) are skipped over, except when the type
specifier is [, c, or n.
• The input data items are read from the string “s”, except when the type specifier is n. The input data items are
defined as the longest input stream of the first partial stream of the string indicated by the type specifier (but
up to the maximum field width if so specified). The character next to the input data items is interpreted as not
having been read. If the length of the input data items is 0, the format command execution fails.
• The input data items (number of input characters with the type specifier n) are converted to the type specified
by the type specifier except the type specifier %. If the input data items do not match the specified type, the
command execution fails. Unless assignment is suppressed by *, the result of the conversion is stored in the
object pointed to by the first argument which follows “format” and has not yet received the result of the
conversion.
The following type specifiers are available:
d ........................... Converts a decimal integer (which may be signed). The corresponding argument must
be a pointer to an integer.
i ............................ Converts an integer (which may be signed). If a number is preceded by 0x or 0X, the
number is interpreted as a hexadecimal integer. If a number is preceded by 0, the
number is interpreted as an octal integer.
Other numbers are regarded as decimal
integers. The corresponding argument must be a pointer to an integer.
o ........................... Converts an octal integer (which may be signed). The corresponding argument must be
a pointer to an integer.
u ........................... Converts an unsigned decimal integer.
The corresponding argument must be a pointer to an unsigned integer.
x ........................... Converts a hexadecimal integer (which may be signed).
e, E, f, g, G........... Floating point value consists of optional sign (+ or –), one or more consecutive decimal
number(s) including decimal point, optional exponent (e or E), and the following optional
signed integer value.
When overflow occurs as a result of conversion, or when
underflow occurs with the conversion result ±∞, a non-normalized number or ±0
becomes the conversion result. The corresponding argument is a pointer to float.
200
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
sscanf (normal model only)
s ...........................
I/O Functions
Input a character string consisting of a non-white-space character string.
The
corresponding argument is a pointer to an integer. 0x or 0X can be allocated at the first
hexadecimal integer. The corresponding argument must be a pointer an array that has
sufficient size to accommodate this character string and a null terminator.
The null
terminator will be automatically added.
[............................
Inputs a character string consisting of expected character groups (called a scanset).
The corresponding argument must be a pointer to the first character of an array that has
sufficient size to accommodate this character string and a null terminator.
terminator will be automatically added.
The null
The format commands continue from this
character up to the closing square bracket (]). The character string (called a scanlist)
enclosed in the square brackets constitutes a scanset except when the character
immediately after the opening square bracket is a circumflex (^).
When the character is a circumflex, all the characters other than a scanlist between the
circumflex and the closing square bracket constitute a scanset.
However, when a
scanlist begins with [ ] or [^], this closing square bracket is contained in the scanlist
and the next closing square list becomes the end of the scanlist.
A hyphen (–) at other than the left or right end of a scanlist is interpreted as the
punctuation mark for hyphenation if the character at the left of the range specifying
hyphen (–) is not smaller than the right-hand character in ASCII code.
c ...........................
Inputs a character string consisting of the number of characters specified by the field
width. (If the field width specification is omitted, 1 is assumed.) The corresponding
argument must be a pointer to the first character of an array that has sufficient size to
accommodate this character string. The null terminator will not be added.
p...........................
Reads an unsigned hexadecimal integer.
The corresponding argument must be a
pointer to void.
n...........................
Receives no input from the string s. The corresponding argument must be a pointer to
an integer. The number of characters that are read thus far by this function from the
string “s” is stored in the object that is pointed to by this pointer.
The %n format
command is not included in the return value assignment count.
%..........................
Reads a % sign. Neither conversion nor assignment takes place.
If a format specification is invalid, the format command execution fails.
If a null terminator appears in the input stream, sscanf will terminate.
If an overflow occurs in an integer conversion (with the d, i, o, u, x, or p format specifier), the higher bits will be
truncated depending on the number of bits of the data type after the conversion.
The syntax of input format commands is illustrated below.
User’s Manual U14872EJ1V0UM
201
CHAPTER 10
LIBRARY FUNCTIONS
sscanf (normal model only)
I/O Functions
Figure 10-3. Syntax of Input Format Commands
White-space
characters:
Format:
Space
Command
\f
White-space
char.
Command:
\n
Ordinary
char.
\r
Format
specifier
\v
Characters except
% and white space
Ordinary characters:
Format command:
\t
%
*
h
Max. field width
Format specifier
I
Max. field width:
Digits
L
Format specifiers:
d
i
scanlist:
^
Characters
except
o
Characters
except
u
x
s
scanlist
c
p
n
f
e
E
g
G
%
202
User’s Manual U14872EJ1V0UM
CHAPTER 10
4-3
LIBRARY FUNCTIONS
printf (normal model only)
I/O Functions
FUNCTION
printf outputs data to SFR according to the format.
HEADER
stdio.h
FUNCTION PROTOTYPE
int printf(const char *format, ...);
Function
printf
Arguments
format ...Pointer to the
character string that indicates
the output conversion
specification
... ... 0 or more arguments to
Return Value
Number of character output to
s (the null character at the end
is not counted)
be converted
EXPLANATION
• (0 or more) arguments following the format are converted and output using the putchar function, according to
the output conversion specification specified in the format.
• The output conversion specification is 0 or more directives. Normal characters (other than the conversion
specification starting with %) are output as is using the putchar function. The conversion specification is
output using the putchar function by fetching and converting the following (0 or more) arguments.
• Each conversion specification is the same as that of the sprintf function.
User’s Manual U14872EJ1V0UM
203
CHAPTER 10
4-4
LIBRARY FUNCTIONS
scanf (normal model only)
I/O Functions
FUNCTION
scanf reads data from SFR according to the format.
HEADER
stdio.h
FUNCTION PROTOTYPE
int scanf(const char *format, ...);
Function
scanf
Arguments
Return Value
format ... Pointer to the
When the character string s is
character string to indicate
input conversion specification
... ... Pointer (0 or more)
not null ... Number of input
items assigned
argument to the object to
assign the converted value
EXPLANATION
• Performs input using the getchar function.
Specifies the input string permitted by the character string
indicated by format. Uses the argument after format as the pointer to an object. format specifies how the
conversion is performed by the input string.
• When there are not enough arguments for format, normal operation is not guaranteed. When the number of
arguments is excessive, the expression will be evaluated but not input.
• format consists of 0 or more directives. The directives are as follows.
(1) One or more null character (character that makes isspace true)
(2) Normal character (other than %)
(3) Conversion indication
• If a conversion ends with an input character that conflicts with the input character, the conflicting input
character is rounded down. The conversion indication is the same as that of the sscanf function.
204
User’s Manual U14872EJ1V0UM
CHAPTER 10
4-5
LIBRARY FUNCTIONS
vprintf (normal model only)
I/O Functions
FUNCTION
vprintf outputs data to SFR according to the format.
HEADER
stdio.h
FUNCTION PROTOTYPE
int vprintf(const char *format,va_list p);
Function
vprintf
Arguments
format ... Pointer to the
character string that indicates
output conversion
specification
p ... Pointer to the argument
Return Value
Number of output characters
(the null character at the end
is not counted)
list
EXPLANATION
• The argument that the pointer of the argument list indicates is converted and output using the putchar
function according to the output conversion specification specified by the format.
• Each conversion specification is the same as that of the sprintf function.
User’s Manual U14872EJ1V0UM
205
CHAPTER 10
4-6
LIBRARY FUNCTIONS
vsprintf (normal model only)
I/O Functions
FUNCTION
vsprintf writes data to character strings according to the format.
HEADER
stdio.h
FUNCTION PROTOTYPE
int vsprintf(char *s,const char * format,va_list p);
Function
vsprintf
Arguments
s ... Pointer to the character
string that writes the output
format ... Pointer to the
Return Value
Number of characters output
to s (the null character at the
end is not counted)
character string that indicates
output conversion
specification
p ... Pointer to the argument
list
EXPLANATION
• Writes out the argument that the pointer of argument list indicates to the character strings that s indicates
according to the output conversion specification specified by format.
• The output specification is the same as that of the sprintf function.
206
User’s Manual U14872EJ1V0UM
CHAPTER 10
4-7
LIBRARY FUNCTIONS
getchar
I/O Functions
FUNCTION
getchar reads a character from SFR
HEADER
stdio.h
FUNCTION PROTOTYPE
int getchar(void);
Function
getchar
Arguments
None
Return Value
A character read from SFR
EXPLANATION
• Returns the value read from SFR symbol P0 (port 0).
• Error check related to reading is not performed.
• To change SFR to read, it is necessary either that the source be changed to be re-registered to the library or
that the user create a new getchar function.
User’s Manual U14872EJ1V0UM
207
CHAPTER 10
4-8
LIBRARY FUNCTIONS
gets
I/O Functions
FUNCTION
gets reads a character string.
HEADER
stdio.h
FUNCTION PROTOTYPE
char *gets(char *s);
Function
gets
Arguments
Return Value
s ... Pointer to input character
Normal ... s
string
If the end of the file is
detected without reading a
character
... Null pointer
EXPLANATION
• Reads a character string using the getchar function and stores in the array that s indicates.
• When the end of the file is detected (getchar function returns -1) or when a line feed character is read, the
reading of a character string ends. The line feed character read is abandoned, and a null character is written
at the end of the last character stored in the array.
• When the return value is normal, it returns s.
• When the end of the file is detected and no character is read in the array, the contents of the array remain
unchanged, and a null pointer is returned.
208
User’s Manual U14872EJ1V0UM
CHAPTER 10
4-9
LIBRARY FUNCTIONS
putchar
I/O Functions
FUNCTION
putchar outputs a character to SFR.
HEADER
stdio.h
FUNCTION PROTOTYPE
int putchar(int c);
Function
putchar
Arguments
c ... Character to be output
Return Value
Character output
EXPLANATION
• Writes the character specified by c to the SFR symbol P0 (port 0) (converted to unsigned char type).
• Error check related to writing is not performed.
• To change SFR to write, it is necessary either that the source is changed and re-registered to the library or
that the user create a new putchar function.
User’s Manual U14872EJ1V0UM
209
CHAPTER 10
LIBRARY FUNCTIONS
4-10 puts
I/O Functions
FUNCTION
puts outputs a character string.
HEADER
stdio.h
FUNCTION PROTOTYPE
int puts(const char *s);
Function
puts
Arguments
s ...Pointer to an output
character string
Return Value
Normal ... 0
When putchar function
returns –1 ... –1
EXPLANATION
• Writes the character string indicated by s using the putchar function, a line feed character is added at the
end of the output.
• Writing of the null character at the end of the character string is not performed.
• When the return value is normal, 0 is returned, and when the putchar function returns –1, –1 is returned.
210
User’s Manual U14872EJ1V0UM
CHAPTER 10
5-1
LIBRARY FUNCTIONS
atoi
atol
Utility Functions
FUNCTION
The string function atoi converts the contents of a decimal integer string to an int value.
The string function atol converts the contents of a decimal integer string to a long int value.
HEADER
stdlib.h
FUNCTION PROTOTYPE
int atoi(const char *nptr);
long int atol(const char *nptr);
Function
atoi
Arguments
nptr... String to be converted
Return Value
• int value if converted
properly
• INT_MAX (32767) if positive
overflow occurs
• INT_MIN (–32768) if
negative overflow occurs
• 0 if the string is invalid
atol
• long int value if converted
properly;
• LONG_MAX (2147483647)
for positive overflow;
• LONG_MIN (–2147483648)
for negative overflow;
• 0 if the string is invalid
User’s Manual U14872EJ1V0UM
211
CHAPTER 10
LIBRARY FUNCTIONS
atoi
atol
Utility Functions
EXPLANATION
atoi
• The atoi function converts the first part of the string pointed to by pointer nptr to an int value.
• The atoi function skips over zero or more white-space characters (for which isspace becomes true) from the
beginning of the string and converts the string from the character next to the skipped white-spaces to an
integer (until other than digits or a null character appears in the string). If no digits to convert are found in the
string, the function returns 0. If an overflow occurs, the function returns INT_MAX (32767) for a positive
overflow and INT_MIN (-32768) for a negative overflow.
atol
• The atol function converts the first part of the string pointed to by pointer nptr to a long int value.
• The atol function skips over zero or more white-space characters (for which isspace becomes true) from the
beginning of the string and converts the string from the character next to the skipped white-spaces to an
integer (until other than digits or a null character appears in the string). If no digits to convert are found in the
string, the function returns 0. If an overflow occurs, the function returns LONG_MAX (2147483647) for a
positive overflow and LONG_MIN (–2147483648) for a negative overflow.
212
User’s Manual U14872EJ1V0UM
CHAPTER 10
5-2
LIBRARY FUNCTIONS
strtol
strtoul
Utility Functions
FUNCTION
The string function strtol converts a string to a long integer.
The string function strtoul converts a string to an unsigned long integer.
HEADER
stdlib.h
FUNCTION PROTOTYPE
long int strtol(const char *nptr,char **endptr,int base);
unsigned long int strtoul(const char *nptr,char **endptr,int base);
Function
strtol
Arguments
nptr... String to be converted
endptr ... Pointer storing
pointer to unrecognizable
section
base ... Specified base
number
Return Value
• long int value if converted
properly
• LONG_MAX
(2147483647) for positive
overflow
• LONG_MIN
(–2147483648) for negative
overflow
• 0 if not converted
strtoul
• unsigned long if converted
properly
• ULONG_MAX
(4294967295U) if overflow
occurs
• 0 if not converted
User’s Manual U14872EJ1V0UM
213
CHAPTER 10
LIBRARY FUNCTIONS
strtol
strtoul
Utility Functions
EXPLANATION
strtol
• The strtol function disassembles the string pointed by pointer nptr into the following three parts.
(1) String of white-space characters that may be empty (to be specified by isspace)
(2) Integer representation by the base determined by the value of base
(3) String of one or more characters that cannot be recognized (including null terminators)
The strtol function converts part (2) of the string into an integer and returns this integer value.
• A base of 0 indicates that the base should be determined from the leading digits of the string. A leading 0x or
0X indicates a hexadecimal number; a leading 0 indicates an octal number; otherwise, the number is
interpreted as decimal. (In this case, the number may be signed).
• If the base is 2 to 36, the set of letters from a to z or A to Z which can be part of a number (and which may be
signed) with any of these bases are taken to represent 10 to 35. A leading 0x or 0X is ignored if the base is
16.
• If endptr is not a null pointer, a pointer to the part (3) of the string is stored in the object pointed to by endptr.
• If the correct value causes an overflow, the function returns LONG_MAX (2147483647) for a positive overflow
or LONG_MIN (-2147483648) for a negative overflow depending on the sign and sets errno to ERANGE (2).
• If the string (2) is empty or the first non-white-space character of the string (2) is not appropriate for an integer
with the given base, the function performs no conversion and returns 0. In this case, the value of the string
nptr is stored in the object pointed to by endptr (if it is not a null string). This holds true with the bases 0 and
2 to 36.
strtoul
• The strtoul function disassembles the string pointed by pointer nptr into the following three parts.
(1) String of white-space characters that may be empty (to be specified by isspace)
(2) Integer representation by the base determined by the value of base
(3) String of one or more characters that cannot be recognized (including null terminators)
The strtoul function converts part (2) of the string into a unsigned integer and returns this unsigned integer
value.
• A base of 0 indicates that the base should be determined from the leading digits of the string. A leading 0x or
0X indicates a hexadecimal number; a leading 0 indicates an octal number; otherwise, the number is
interpreted as decimal.
• If the base is 2 to 36, the set of letters from a to z or A to Z which can be part of a number (and which may be
signed) with any of these bases are taken to represent 10 to 35. A leading 0x or 0X is ignored if the base is
16.
• If endptr is not a null pointer, a pointer to the part (3) of the string is stored in the object pointed to by endptr.
214
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
strtol
strtoul
Utility Functions
• If the correct value causes an overflow, the function returns ULONG_MAX (4294967295U) and sets errno to
ERANGE (2).
• If the string (2) is empty or the first non-white-space character of the string (2) is not appropriate for an
integer with the given base, the function performs no conversion and returns 0. In this case, the value of the
string nptr is stored in the object pointed to by endptr (if it is not a null string). This holds true with the bases
0 and 2 to 36.
User’s Manual U14872EJ1V0UM
215
CHAPTER 10
5-3
LIBRARY FUNCTIONS
calloc
Utility Functions
FUNCTION
The memory function calloc allocates an array area and then initializes the area to 0.
HEADER
stdlib.h
FUNCTION PROTOTYPE
void *calloc(size_t nmemb,size_t size);
Function
calloc
Arguments
nmemb ... Number of
members in the array
size ... Size of each member
Return Value
• Pointer to the beginning of
the allocated area if the
requested size is allocated
• Null pointer if the requested
size is not allocated
EXPLANATION
• The calloc function allocates an area for an array consisting of n number of members (specified by nmemb),
each of which has the number of bytes specified by size and initializes the area (array members) to zero.
• Returns the pointer to the beginning of the allocated area if the requested size is allocated.
• Returns the null pointer if the requested size is not allocated.
• The memory allocation will start from a break value and the address next to the allocated space will become a
new break value. See 5-11 brk for break value setting with the memory function brk.
216
User’s Manual U14872EJ1V0UM
CHAPTER 10
5-4
LIBRARY FUNCTIONS
free
Utility Functions
FUNCTION
The memory function free releases the allocated block of memory.
HEADER
stdlib.h
FUNCTION PROTOTYPE
void free(void *ptr);
Function
free
Arguments
ptr ... Pointer to the beginning
Return Value
None
of block to be released
EXPLANATION
• The free function releases the allocated space (before a break value) pointed to by ptr. (malloc, calloc, or
realloc called after free will allocate space from ptr.)
• If ptr does not point to the allocated space, the free will take no action. (Freeing the allocated space is
performed by setting ptr as a new break value.)
User’s Manual U14872EJ1V0UM
217
CHAPTER 10
5-5
LIBRARY FUNCTIONS
malloc
Utility Functions
FUNCTION
The memory function malloc allocates a block of memory.
HEADER
stdlib.h
FUNCTION PROTOTYPE
void *malloc(size_t size);
Function
malloc
Arguments
size ... Size of memory block
to be allocated
Return Value
• Pointer to the beginning of
the allocated area if the
requested size is allocated
• Null pointer if the requested
size is not allocated
EXPLANATION
• The malloc function allocates a block of memory for the number of bytes specified by size and returns a
pointer to the first byte of the allocated area.
• If memory cannot be allocated, the function returns a null pointer.
• This memory allocation will start from a break value and the address next to the allocated area will become a
new break value. See 5-11 brk for break value setting with the memory function brk.
218
User’s Manual U14872EJ1V0UM
CHAPTER 10
5-6
LIBRARY FUNCTIONS
realloc
Utility Functions
FUNCTION
The memory function realloc reallocates a block of memory (namely, changes the size of the allocated memory).
HEADER
stdlib.h
FUNCTION PROTOTYPE
void *realloc(void *ptr,size_t size);
Function
realloc
Arguments
Return Value
ptr ... Pointer to the beginning
• Pointer to the beginning of
the reallocated space if the
requested size is
reallocated
• Pointer to the beginning of
the allocated space if ptr is
of block previously allocated
size ... New size to be given to
this block
a null pointer
• Null pointer if the requested
size is not reallocated or
“ptr” is not a null pointer
EXPLANATION
• The realloc function changes the size of the allocated space (before a break value) pointed to by ptr to that
specified by size. If the value of size is greater than the size of the allocated space, the contents of the
allocated space up to the original size will remain unchanged. The realloc function allocates only for the
increased space. If the value of size is less than the size of the allocated space, the function will free the
reduced space of the allocated space.
• If ptr is a null pointer, the realloc function will newly allocate a block of memory of the specified size (same as
malloc).
• If ptr does not point to the block of memory previously allocated or if no memory can be allocated, the
function executes nothing and returns a null pointer.
• Reallocation will be performed by setting the address of ptr plus the number of bytes specified by size as a
new break value.
User’s Manual U14872EJ1V0UM
219
CHAPTER 10
5-7
LIBRARY FUNCTIONS
abort
Utility Functions
FUNCTION
The program control function abort causes immediate, abnormal termination of a program.
HEADER
stdlib.h
FUNCTION PROTOTYPE
void abort(void);
Function
abort
Arguments
None
Return Value
No return
EXPLANATION
• The abort function loops and can never return to its caller.
• The user must create the abort processing routine.
220
User’s Manual U14872EJ1V0UM
CHAPTER 10
5-8
LIBRARY FUNCTIONS
atexit
exit
Utility Functions
FUNCTION
atexit registers the function called at the normal termination.
exit terminates a program.
HEADER
stdlib.h
FUNCTION PROTOTYPE
int atexit(void(*func)(void));
void exit(int status);
Function
atexit
Arguments
func ... Pointer to function to
be registered
exit
status ... Status value
Return Value
• 0 if function is registered as
wrap-up function
• 1 if function cannot be
registered
No return.
indicating termination
EXPLANATION
atexit
• The atexit function registers the wrap-up function pointed to by func so that it is called without argument upon
normal program termination by calling exit or returning from main.
• Up to 32 wrap-up functions may be established. If the wrap-up function can be registered, atexit returns 0. If
no more wrap-up functions can be registered because 32 wrap-up functions have already been registered, the
function returns 1.
exit
• The exit function causes immediate, normal termination of a program.
• This function calls the wrap-up functions in the reverse of the order in which they were registered with atexit.
• The exit function loops and can never return to its caller.
• The user must create the exit processing routine.
User’s Manual U14872EJ1V0UM
221
CHAPTER 10
5-9
LIBRARY FUNCTIONS
abs
labs
Utility Functions
FUNCTION
The mathematical function abs returns the absolute value of its int type argument.
The mathematical function labs returns the absolute value of its long type argument.
HEADER
stdlib.h
FUNCTION PROTOTYPE
int abs(int j);
long int labs(long int j);
Function
abs
Arguments
Return Value
j ... Absolute value to be
• Absolute value of j if j falls
obtained
within:
–32767 ≤ j ≤ 32767
• –32768 (0x8000) if j is
–32768
labs
• Absolute value of j if j falls
within
–2147483647 ≤ j ≤
2147483647
• –2147483648
(0x80000000) if the value of
j is –2147483648
EXPLANATION
abs
• The abs returns the absolute value of its int type argument.
• If j is –32768, the function returns –32768.
labs
• The labs returns the absolute value of its long type argument.
• If the value of j is –2147483648, the function returns –2147483648.
222
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-10 div (normal model only)
ldiv (normal model only)
Utility Functions
FUNCTION
The mathematical function div performs the integer division of numerator divided by denominator.
The mathematical function ldiv performs the long integer division of numerator divided by denominator.
HEADER
stdlib.h
FUNCTION PROTOTYPE
div_t div(int numer,int denom);
ldiv_t ldiv(long int numer,long int denom);
Function
div
Arguments
numer ... Numerator of the
division
denom ... Denominator of the
ldiv
division
Return Value
Quotient to the quot element
and the remainder to the rem
element of div_t type member
Quotient to the quot element
and the remainder to the rem
element of ldiv_t type
member
EXPLANATION
div
• The div function performs the integer division of numerator divided by denominator.
• The absolute value of the quotient is defined as the largest integer not greater than the absolute value of
numer divided by the absolute value of denom. The remainder always has the same sign as the result of the
division (plus if numer and denom have the same sign; otherwise minus).
• The remainder is the value of numer – denom*quotient.
• If denom is 0, the quotient becomes 0 and the remainder becomes numer.
• If numer is –32768 and denom is –1, the quotient becomes -32768 and the remainder becomes 0.
ldiv
• The ldiv function performs the long integer division of numerator divided by denominator.
• The absolute value of the quotient is defined as the largest long int type integer not greater than the absolute
value of numer divided by the absolute value of denom. The remainder always has the same sign as the
result of the division (plus if numer and denom have the same sign; otherwise minus).
• The remainder is the value of numer – denom*quotient.
• If denom is 0, the quotient becomes 0 and the remainder becomes numer.
• If numer is –2147483648 and denom is –1, the quotient becomes –2147483648 and the remainder becomes
0.
User’s Manual U14872EJ1V0UM
223
CHAPTER 10
LIBRARY FUNCTIONS
5-11 brk
sbrk
Utility Functions
FUNCTION
The memory function brk sets a break value.
The memory function sbrk increments or decrements the set break value.
HEADER
stdlib.h
FUNCTION PROTOTYPE
int brk(char *endds);
char *sbrk(int incr);
Function
brk
Arguments
endds ... Break value to be
set block to be released
sbrk
incr ... Value (bytes) by which
set break value is to be
incremented/decremented.
Return Value
• 0 if break value is set
properly
• –1 if break value cannot be
changed
• Old break value if
incremented or
decremented properly
• –1 if old break value cannot
be incremented or
decremented
EXPLANATION
brk
• The brk function sets the value given by endds as a break value (the address next to the end address of an
allocated block of memory).
• If endds is outside the permissible address range, the function sets no break value and sets errno to
ENOMEM (3).
sbrk
• The sbrk function increments or decrements the set break value by the number of bytes specified by incr.
(Increment or decrement is determined by the plus or minus sign of incr.)
• If the incremented or decremented break value is outside the permissible address range, the function does
not change the original break value and sets errno to ENOMEM (3).
224
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-12 atof
strtod
Utility Functions
FUNCTION
The string function atof converts the contents of a decimal integer string to a double value.
The string function strtod converts the contents of a string to a double value.
HEADER
stdlib.h
FUNCTION PROTOTYPE
double atof(const char *nptr);
double strtod(const char *nptr, char **endptr);
Function
atof
Arguments
nptr ... String to be converted
Return Value
• Converted value if
converted properly
• HUGE_VAL (with sign of
overflowed value) if positive
overflow occurs
• 0 if negative overflow
occurs
• 0 if the string is invalid
strtod
nptr ... String to be converted
endptr … Pointer storing
pointer to unrecognizable
block
• Converted value if
converted properly
• HUGE_VAL (with sign of
overflowed value) if positive
overflow occurs
• 0 if negative overflow
occurs
• 0 if the string is invalid
User’s Manual U14872EJ1V0UM
225
CHAPTER 10
LIBRARY FUNCTIONS
atof
strtod
Utility Functions
EXPLANATION
atof
• The atof function converts the string pointed to by pointer nptr to a double value.
• The atof function skips over zero or more white-space characters (for which isspace becomes true) from the
beginning of the string and converts the string from the character next to the skipped white-spaces to a
floating-point number (until other than digits or a null character appears in the string).
• A floating-point number is returned when converted properly.
• If an overflow occurs on conversion, HUGE_VAL with the sign of the overflowed value is returned and
ERANGE is set to errno.
• If valid digits are deleted due to an underflow or an overflow, a non-normalized number and ±0 are returned
respectively, and ERANGE is set to errno.
• IF conversion cannot be performed, 0 is returned.
strtod
• The strtod function converts the string pointed to by pointer nptr to a double value.
• The strtod function skips over zero or more white-space characters (for which isspace becomes true) from
the beginning of the string and converts the string from the character next to the skipped white-spaces to a
floating-point number (until other than digits or a null character appears in the string).
• A floating-point number is returned when converted properly.
• If an overflow occurs on conversion, HUGE_VAL with the sign of the overflowed value is returned and
ERANGE is set to errno.
• If valid digits are deleted due to an underflow or an overflow, a non-normalized number and ±0 are returned
respectively, and ERANGE is set to errno. In addition, endptr stores a pointer for next character string at that
time.
• IF conversion cannot be performed, 0 is returned.
226
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-13 itoa
ltoa (normal model only)
ultoa (normal model only)
Utility Functions
FUNCTION
The string function itoa converts an int integer to its string equivalent.
The string function ltoa converts a long int integer to its string equivalent.
The string function ultoa converts an unsigned long integer to its string equivalent.
HEADER
stdlib.h
FUNCTION PROTOTYPE
char *itoa(int value,char *string,int radix);
char *ltoa(long value,char *string,int radix);
char *ultoa(unsigned long value,char *string,int radix);
Function
itoa,
ltoa,
ultoa
Arguments
value ... String to which
integer is to be converted
string ... Pointer to the
conversion result
radix ... Base of output string
Return Value
• Pointer to the converted
string if converted properly
• Null pointer if not converted
properly
EXPLANATION
itoa, ltoa, ultoa
• The itoa, ltoa, and ultoa functions all convert the integer value specified by value to its string equivalent
which is terminated with a null character and store the result in the area pointed to by “string”.
• The base of the output string is determined by radix, which must be in the range 2 through 36. Each function
performs conversion based on the specified radix and returns a pointer to the converted string.
If the
specified radix is outside the range 2 through 36, the function performs no conversion and returns a null
pointer.
User’s Manual U14872EJ1V0UM
227
CHAPTER 10
LIBRARY FUNCTIONS
5-14 rand
srand
Utility Functions
FUNCTION
The mathematical function rand generates a sequence of psuedo-random numbers.
The mathematical function srand sets a starting value (seed) for the sequence generated by rand.
HEADER
stdlib.h
FUNCTION PROTOTYPE
int rand(void);
void srand(unsigned int seed);
Function
Arguments
Return Value
rand
None
Psuedo-random integer in the
range of 0 to RAND_MAX
srand
seed ... Starting value for
None
psuedo-random number
generator
EXPLANATION
rand
• Each time the rand function is called, it returns a psuedo-random integer in the range of 0 to RAND_MAX.
srand
• The srand function sets a starting value for a sequence of random numbers. seed is used to set a starting
point for a progression of random numbers that is a return value when rand is called. If the same seed value
is used, the sequence of psuedo-random numbers is the same when srand is called again.
• Calling rand before srand is used to set a seed is the same as calling rand after srand has been called with
seed = 1. (The default seed is 1.)
228
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-15 bsearch (normal model only)
Utility Functions
FUNCTION
The bsearch function performs a binary search.
HEADER
stdlib.h
FUNCTION PROTOTYPE
void *bsearch(const void *key,const void *base,size_t nmemb,
size_t size,int (*compare)(const void *,const void *));
Function
bsearch
Arguments
Return Value
key ... Pointer to key for which
• Pointer to the first member
that matches “key” if the
array contains the key;
• Null pointer if the key is not
contained in the array
search is made
base ... Pointer to sorted array
which contains information to
search
nmemb ... Number of array
elements
size ... Size of an array
compare ... Pointer to function
used to compare two keys
EXPLANATION
• The bsearch function performs a binary search on the sorted array pointed to by base and returns a pointer
to the first member that matches the key pointed to by key. The array pointed to by base must be an array
which consists of nmemb number of members each of which has the size specified by size and must have
been sorted in ascending order.
• The function pointed to by compare takes two arguments (key as the 1st argument and array element as the
2nd argument), compares the two arguments, and returns:
- Negative value if the 1st argument is less than the 2nd argument
- 0 if both arguments are equal
- Positive integer if the 1st argument is greater than the 2nd argument
• When the -ZR option is specified, the function passed to the argument of the bsearch function must be a
pascal function.
User’s Manual U14872EJ1V0UM
229
CHAPTER 10
LIBRARY FUNCTIONS
5-16 qsort (normal model only)
Utility Functions
FUNCTION
The qsort function sorts the members of a specified array using a quicksort algorithm.
HEADER
stdlib.h
FUNCTION PROTOTYPE
void qsort(void *base,size_t nmemb,size_t size,
int (*compare)(const void *,const void *));
Function
qsort
Arguments
base ... Pointer to array to be
Return Value
None
sorted
nmemb ... Number of
members in the array
size ... Size of an array
member
compare ... Pointer to function
used to compare two keys
EXPLANATION
• The qsort function sorts the members of the array pointed to by base in ascending order. The array pointed
to by base consists of nmemb number of members each of that has the size specified by size.
• The function pointed to by compare takes two arguments (array elements 1 and 2), compares the two
arguments, and returns:
• The array element 1 as the 1st argument and array element 2 as the 2nd argument
Negative value if the 1st argument is less than the 2nd argument
0 if both arguments are equal
Positive integer if the 1st argument is greater than the 2nd argument
• If the two array elements are equal, the element nearest to the top of the array will be sorted first.
• When the -ZR option is specified, the function passed to the argument of the qsort function must be a pascal
function.
230
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-17 strbrk
Utility Functions
FUNCTION
strbrk sets a break value.
HEADER
stdlib.h
FUNCTION PROTOTYPE
int strbrk(char *endds);
Function
strbrk
Arguments
ends ... Break value to set
Return Value
Normal ... 0
When a break value cannot be
changed ... –1
EXPLANATION
• Sets the value given by endds to the break value (the address following the address at the end of the area to
be allocated).
• When endds is out of the permissible range, the break value is not changed. ENOMEM(3) is set to errno
and –1 is returned.
User’s Manual U14872EJ1V0UM
231
CHAPTER 10
LIBRARY FUNCTIONS
5-18 strsbrk
Utility Functions
FUNCTION
strsbrk increases/decreases a break value.
HEADER
stdlib.h
FUNCTION PROTOTYPE
char *strsbrk(int incr);
Function
strsbrk
Arguments
incr ... Amount to
increase/decrease a break
value
Return Value
Normal ... Old break value
When a break value cannot be
increased/decreased ... –1
EXPLANATION
• incr byte increases/decreases a break value (depending on the sign of incr).
• When the break value is out of the permissible range after increasing/decreasing, a break value is not
changed. ENOMEM(3) is set to errno, and –1 is returned.
232
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-19 stritoa
strltoa (normal model only)
strultoa (normal model only)
Utility Functions
FUNCTION
stritoa converts int to a character string.
strltoa converts long to a character string.
strultoa converts unsigned long to a character string.
HEADER
stdlib.h
FUNCTION PROTOTYPE
char *stritoa(int value,char *string,int radix);
char *strltoa(long value,char *string,int radix);
char *strultoa(unsigned long value,char *string,int radix);
Function
stritoa
strltoa
strultoa
Arguments
value ... Character string to
convert
string ... Pointer to conversion
Return Value
Normal ... Pointer to the
converted character string
Other ... Null pointer
result
radix ... Radix to specify
EXPLANATION
stritoa, strltoa, strultoa
• Converts the specified numeric value value to a character string that ends with a null character, and stores
the result in the area specified by string. The conversion is performed using the specified radix, and the
pointer to the converted character string will be returned.
• radix must be a value in the range of 2 to 36. In other cases, the conversion is not performed and a null
pointer is returned.
User’s Manual U14872EJ1V0UM
233
CHAPTER 10
6-1
LIBRARY FUNCTIONS
memcpy
memmove
Character String/Memory Functions
FUNCTION
The memory function memcpy copies a specified number of characters from a source area of memory to a
destination area of memory.
The memory function memmove is identical to memcpy, except that it allows overlap between the source and
destination areas.
HEADER
string.h
FUNCTION PROTOTYPE
void *memcpy (void *s1, const void *s2, size_t n);
void *memmove (void *s1, const void *s2, size_t n);
Function
memcpy,
memmove
Arguments
s1 ... Pointer to object into
Return Value
Value of s1
which data is to be copied
s2 ... Pointer to object
containing data to be copied
n ... Number of characters to
be copied
EXPLANATION
memcpy
• The memcpy function copies n number of consecutive bytes from the object pointed to by s2 to the object
pointed to by s1.
• If s2<s1<s2+n (s1 and s2 overlap), the memory copy operation by memcpy is not guaranteed (because
copying starts in sequence from the beginning of the area).
memmove
• The memmove function also copies n number of consecutive bytes from the object pointed to by s2 to the
object pointed to by s1.
• Even if s1 and s2 overlap, the function performs memory copying properly.
234
User’s Manual U14872EJ1V0UM
CHAPTER 10
6-2
LIBRARY FUNCTIONS
strcpy
strncpy
Character String/Memory Functions
FUNCTION
The string function strcpy is used to copy the contents of one character string to another.
The string function strncpy is used to copy up to a specified number of characters from one character string to
another.
HEADER
string.h
FUNCTION PROTOTYPE
char *strcpy (char *s1, const char *s2);
char *strncpy (char *s1, const char *s2, size_t n);
Function
strcpy,
strncpy
Arguments
s1... Pointer to copy
Return Value
Value of s1
destination array
s2 ... Pointer to copy source
array
n ... Number of characters to
be copied
EXPLANATION
strcpy
• The strcpy function copies the contents of the character string pointed to by s2 to the array pointed to by s1
(including the terminating character).
• If s2 < s1 ≤ (s2 + Character length to be copied), the behavior of strcpy is not guaranteed (as copying starts
in sequence from the beginning, not from the specified string).
strncpy
• The strncpy function copies up to the characters specified by n from the string pointed to by s2 to the array
pointed to by s1.
• If s2 < s1 ≤ (s2 + Character length to be copied or minimum value of s2 + n – 1), the behavior of strncpy is
not guaranteed (as copying starts in sequence from the beginning, not from the specified string).
• If the string pointed by s2 is less than the characters specified by n, nulls will be appended to the end of s1
until n characters have been copied. If the string pointed to by s2 is longer than n characters, the resultant
string that is pointed to by s1 will not be null terminated.
User’s Manual U14872EJ1V0UM
235
CHAPTER 10
6-3
LIBRARY FUNCTIONS
strcat
strncat
Character String/Memory Functions
FUNCTION
The string function strcat concatenates one character string to another.
The string function strncat concatenates up to a specified number of characters from one character string to
another.
HEADER
string.h
FUNCTION PROTOTYPE
char *strcat (char *s1, const char *s2);
char *strncat (char *s1, const char *s2, size_t n);
Function
strcat,
strncat
Arguments
s1... Pointer to a string to
Return Value
Value of s1
which a copy of another string
(s2) is to be concatenated
s2 ... Pointer to a string, copy
of which is to be concatenated
to another string (s1).
n ... Number of characters to
be concatenated
EXPLANATION
strcat
• The strcat function concatenates a copy of the string pointed to by s2 (including the null terminator) to the
string pointed to by s1. The null terminator originally ending s1 is overwritten by the first character of s2.
• When copying is performed between objects overlapping each other, the operation is not guaranteed.
strncat
• The strncat function concatenates not more than the characters specified by n of the string pointed to by s2
(excluding the null terminator) to the string pointed to by s1. The null terminator originally ending s1 is
overwritten by the first character of s2.
• If the string pointed to by s2 has fewer characters than specified by n, the strncat function concatenates the
string including the null terminator. If there are more characters than specified by n, the n character section is
concatenated starting from the top.
• The null terminator must always be concatenated.
• When copying is performed between objects overlapping each other, the operation is not guaranteed.
236
User’s Manual U14872EJ1V0UM
CHAPTER 10
6-4
LIBRARY FUNCTIONS
memcmp
Character String/Memory Functions
FUNCTION
The memory function memcmp compares two data objects, with respect to a given number of characters.
HEADER
string.h
FUNCTION PROTOTYPE
int memcmp (const void *s1, const void *s2, size_t n);
Function
memcmp
Arguments
s1, s2 ... Pointers to two data
objects to be compared
n ... Number of characters to
compare
Return Value
• 0 if s1 and s2 are equal
• Positive value if s1 is
greater than s2; negative
value if s1 is less than s2
(s1 – s2)
EXPLANATION
• The memcmp function compares the data object pointed to by s1 with the data object pointed to by s2 with
respect to the number of bytes specified by n.
• If the two objects are equal, the function returns 0.
• The function returns a positive value if the object s1 is greater than the object s2 and a negative value if s1 is
less than s2.
User’s Manual U14872EJ1V0UM
237
CHAPTER 10
6-5
LIBRARY FUNCTIONS
strcmp
strncmp
Character String/Memory Functions
FUNCTION
The string function strcmp compares two character strings.
The string function strncmp compares not more than a specified number of characters from two character
strings.
HEADER
string.h
FUNCTION PROTOTYPE
char *strcmp (char *s1, const char *s2);
char *strncmp (char *s1, const char *s2, size_t n);
Function
strcmp
Arguments
s1... Pointer to one string to
• 0 if s1 is equal to s2
be compared
s2 ... Pointer to the other
• Integer less than 0 or
greater than 0 if s1 is less
than or greater than s2 (s1
– s2)
string to be compared
strncmp
Return Value
s1... Pointer to one string to
be compared
s2 ... Pointer to the other
string to be compared
n ... Number of characters to
be compared
• 0 if s1 is equal to s2 within
characters specified by n
• Integer less than 0 or
greater than 0 if s1 is less
than or greater than s2 (s1
– s2) within characters
specified by n
EXPLANATION
strcmp
• The strcmp function compares the two null terminated strings pointed to by s1 and s2, respectively.
• If s1 is equal to s2, the function returns 0. If s1 is less than or grater than s2, the function returns an integer
less than 0 (a negative number) or greater than 0 (a positive number) (s1 – s2).
strncmp
• The strncmp function compares not more than the characters specified by n from the two null terminated
strings pointed to by s1 and s2, respectively.
• If s1 is equal to s2 within the specified characters, the function returns 0. If s1 is less than or greater than s2
within the specified characters, the function returns an integer less than 0 (a negative number) or greater than
0 (a positive number) (s1 – s2).
238
User’s Manual U14872EJ1V0UM
CHAPTER 10
6-6
LIBRARY FUNCTIONS
memchr
Character String/Memory Functions
FUNCTION
The memory function memchr converts a specified character to unsigned char, searches for it, and returns a
pointer to the first occurrence of this character in an object of a given size.
HEADER
string.h
FUNCTION PROTOTYPE
void *memchr (const void *s, int c, size_t
Function
memchr
n);
Arguments
s ... Pointer to objects in
memory subject to search
c ... Character to be searched
n ... Number of bytes to be
Return Value
• Pointer to the first
occurrence of c if c is found
• Null pointer if c is not found
searched
EXPLANATION
• The memchr function first converts the character specified by c to unsigned char and then returns a pointer
to the first occurrence of this character within the n number of bytes from the beginning of the object pointed
to by s.
• If the character is not found, the function returns a null pointer.
User’s Manual U14872EJ1V0UM
239
CHAPTER 10
6-7
LIBRARY FUNCTIONS
strchr
strrchr
Character String/Memory Functions
FUNCTION
The string function strchr returns a pointer to the first occurrence of a specified character in a string.
The string function strrchr returns a pointer to the last occurrence of a specified character in a string.
HEADER
string.h
FUNCTION PROTOTYPE
char *strchr (const char *s, int c);
char *strrchr (const char *s, int c);
Function
strchr,
strrchr
Arguments
s... Pointer to string to be
searched
c ... Character specified for
search
Return Value
• Pointer indicating the first or
last occurrence of c in string
s if c is found in s
• Null pointer if c is not found
in s
EXPLANATION
strchr
• The strchr function searches the string pointed to by s for the character specified by c and returns a pointer
to the first occurrence of c (converted to char type) in the string.
• The null terminator is regarded as part of the string.
• If the specified character is not found in the string, the function returns a null pointer.
strrchr
• The strrchr function searches the string pointed to by s for the character specified by c and returns a pointer
to the last occurrence of c (converted to char type) in the string.
• The null terminator is regarded as part of the string.
• If no match is found, the function returns a null pointer.
240
User’s Manual U14872EJ1V0UM
CHAPTER 10
6-8
LIBRARY FUNCTIONS
strspn
strcspn
Character String/Memory Functions
FUNCTION
The string function strspn returns the length of the initial substring of a string that is made up of only those
characters contained in another string.
The string function strcspn returns the length of the initial substring of a string that is made up of only those
characters not contained in another string.
HEADER
string.h
FUNCTION PROTOTYPE
size_t strspn (const char *s1, const char *s2);
size_t strcspn (const char *s1, const char *2);
Function
strspn
Arguments
s1... Pointer to string to be
searched
s2 ... Pointer to string whose
characters are specified for
strcspn
match
Return Value
Length of substring of the
string s1 that is made up of
only those characters
contained in the string s2
Length of substring of the
string s1 that is made up of
only those characters not
contained in the s2
EXPLANATION
strspn
• The strspn function returns the length of the substring of the string pointed to by s1 that is made up of only
those characters contained in the string pointed to by s2. In other words, this function returns the index of the
first character in the string s1 that does not match any of the characters in the string s2.
• The null terminator of s2 is not regarded as part of s2.
strcspn
• The strcspn function returns the length of the substring of the string pointed to by s1 that is made up of only
those characters not contained in the string pointed to by s2. In other words, this function returns the index of
the first character in the string s1 that matches any of the characters in the string s2.
• The null terminator of s2 is not regarded as part of s2.
User’s Manual U14872EJ1V0UM
241
CHAPTER 10
6-9
LIBRARY FUNCTIONS
strpbrk
Character String/Memory Functions
FUNCTION
The string function strpbrk returns a pointer to the first character in a string to be searched that matches any
character in a specified string.
HEADER
string.h
FUNCTION PROTOTYPE
char *strpbrk (const char *s1, const char *s2);
Function
strpbrk
Arguments
s1... Pointer to string to be
searched
s2 ... Pointer to string whose
characters are specified for
match
Return Value
• Pointer to the first character
in the string s1 that
matches any character in
the string s2 if any match is
found
• Null pointer if no match is
found
EXPLANATION
• The strpbrk function returns a pointer to the first character in the string pointed to by s1 that matches any
character in the string pointed to by s2.
• If none of the characters in the string s2 is found in the string s1, the function returns a null pointer.
242
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-10 strstr
Character String/Memory Functions
FUNCTION
The string function strstr returns a pointer to the first occurrence in the string to be searched of a specified
string.
HEADER
string.h
FUNCTION PROTOTYPE
char *strstr (const char *s1, const char *s2);
Function
strstr
Arguments
s1... Pointer to string to be
searched
s2 ... Pointer to specified string
Return Value
• Pointer to the first
appearance in the string s1
of the string s2 if s2 is
found in s1
• Null pointer if s2 is not
found in s1
• Value of s1 if s2 is a null
string
EXPLANATION
• The strstr function returns a pointer to the first appearance in the string pointed to by s1 of the string pointed
to by s2 (except the null terminator of s2).
• If the string s2 is not found in the string s1, the function returns a null pointer.
• If the string s2 is a null string, the function returns the value of s1.
User’s Manual U14872EJ1V0UM
243
CHAPTER 10
LIBRARY FUNCTIONS
6-11 strtok
Character String/Memory Functions
FUNCTION
The string function strtok returns a pointer to a token taken from a string (by disassembling it into a string
consisting of characters other than delimiters).
HEADER
string.h
FUNCTION PROTOTYPE
char *strtok (char *s1, const char *s2);
Function
strtok
Arguments
s1... Pointer to string from
which tokens are to be
obtained or null pointer
s2 ... Pointer to string
Return Value
• Pointer to the first character
of a token if it is found
• Null pointer if there is no
token to return
containing delimiters of token
EXPLANATION
• A token is a string consisting of characters other than delimiters in the string to be specified.
• If s1 is a null pointer, the string pointed to by the saved pointer in the previous strtok call will be
disassembled. However, if the saved pointer is a null pointer, the function returns a null pointer without doing
anything.
• If s1 is not a null pointer, the string pointed to by s1 will be disassembled.
• The strtok function searches the string pointed to by s1 for any character not contained in the string pointed
to by s2. If no character is found, the function changes the saved pointer to a null pointer and returns it. If
any character is found, the character becomes the first character of a token.
• If the first character of a token is found, the function searches for any characters contained in the string s2
after the first character of the token. If none of the characters is found, the function changes the saved
pointer to a null pointer. If any of the characters is found, the character is overwritten by a null character and
a pointer to the next character becomes a pointer to be saved.
• The function returns a pointer to the first character of the token.
244
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-12 memset
Character String/Memory Functions
FUNCTION
The memory function memset initializes a specified number of bytes in an object in memory with a specified
character.
HEADER
string.h
FUNCTION PROTOTYPE
void *memset (void *s, int c, size_t
Function
memset
n);
Arguments
s ... Pointer to object in
Return Value
Value of s
memory to be initialized
c ... Character whose value is
to be assigned to each byte
n ... Number of bytes to be
initialized
EXPLANATION
• The memset function first converts the character specified by c to unsigned char and then assigns the value
of this character to the n number of bytes from the beginning of the object pointed to by s.
User’s Manual U14872EJ1V0UM
245
CHAPTER 10
LIBRARY FUNCTIONS
6-13 strerror
Character String/Memory Functions
FUNCTION
The strerror function returns a pointer to the location which stores a string describing the error message
associated with a given error number.
HEADER
string.h
FUNCTION PROTOTYPE
char *strerror (int errnum);
Function
strerror
Arguments
errnum ... Error number
Return Value
• Pointer to string describing
error message if message
associated with error
number exists
• Null pointer if no message
associated with error
number exists
EXPLANATION
• The strerror function returns a pointer to one of the following strings associated with the value of errnum.
0....................... “Error 0”
1 (EDOM)......... “Argument too large”
2 (ERANGE) .... “Result too large”
3 (ENOMEM) ... “Not enough memory”
Otherwise, the function returns a null pointer.
246
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-14 strlen
Character String/Memory Functions
FUNCTION
The string function strlen returns the length of a character string.
HEADER
string.h
FUNCTION PROTOTYPE
size_t strlen (const char *s);
Function
strlen
Arguments
s... Pointer to character string
Return Value
Length of string s
EXPLANATION
• The strlen function returns the length of the null terminated string pointed to by s.
User’s Manual U14872EJ1V0UM
247
CHAPTER 10
LIBRARY FUNCTIONS
6-15 strcoll
Character String/Memory Functions
FUNCTION
strcoll compares two character strings based on the information specific to the area.
HEADER
string.h
FUNCTION PROTOTYPE
int strcoll (const char *s1, const char *s2) ;
Function
strcoll
Arguments
s1 ... Pointer to comparison
character string
s2 ... Pointer to comparison
character string
Return Value
When character strings s1
and s2 are equal ... 0
When character strings s1
and s2 are different
... The difference between the
values whose first different
characters are converted to int
(character of s1 – character of
s2)
EXPLANATION
• This compiler does not support operations specific to the cultural sphere. The operations are the same as
that of strcmp.
248
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-16 strxfrm
Character String/Memory Functions
FUNCTION
strxfrm converts a character string based on the information specific to the area.
HEADER
string.h
FUNCTION
size_t strxfrm (char *s1, const char *s2, size_t n) ;
Function
strxfrm
Arguments
s1 ... Pointer to a compared
character string
s2 ... Pointer to a compared
character string
n ... Maximum number of
characters in s1
Return Value
Returns the length of the
character string of the result of
the conversion (does not
include a character string to
indicate the end)
If the returned value is n or
more, the contents of the
array indicated by s1 is
undefined.
EXPLANATION
• This compiler does not support operations specific to the cultural sphere. The operations are the same as
those of the following functions.
strncpy (s1, s2, c) ;
return (strlen (s2)) ;
User’s Manual U14872EJ1V0UM
249
CHAPTER 10
7-1
LIBRARY FUNCTIONS
acos (normal model only)
Mathematical Functions
FUNCTION
acos finds acos.
HEADER
math.h
FUNCTION PROTOTYPE
double acos (double x) ;
Function
acos
Arguments
x ... Numeric value on which
operation is performed
Return Value
When –1 ≤ x ≤ 1 ... acos of x
When x < –1, 1 < x, x = NaN
... NaN
EXPLANATION
• Calculates acos of x (range between 0 and p).
• When x is non-numeric, NaN is returned.
• In the case of the definition area error of x < –1, 1 < x, NaN is returned and EDOM is set.
250
User’s Manual U14872EJ1V0UM
CHAPTER 10
7-2
LIBRARY FUNCTIONS
asin (normal model only)
Mathematical Functions
FUNCTION
asin finds asin.
HEADER
math.h
FUNCTION PROTOTYPE
double asin (double x) ;
Function
asin
Arguments
x ... Numeric value on which
operation is performed
Return Value
When –1 ≤ x ≤ 1 ... asin of x
When x ≤ –1, 1 ≤ x, x = NaN
... NaN
When x = –0 ... –0
When underflow occurs ...
Non-normalized number
EXPLANATION
• Calculates asin (range between –π/2 and +π/2) of x.
• In the case of area error of x < –1, 1 < x, NaN is returned and EDOM is set to errno.
• When x is non-numeric, NaN is returned.
• When x is –0, –0 is returned.
• If an underflow occurs as a result of conversion, a non-normalized number is returned.
User’s Manual U14872EJ1V0UM
251
CHAPTER 10
7-3
LIBRARY FUNCTIONS
atan (normal model only)
Mathematical Functions
FUNCTION
atan finds atan.
HEADER
math.h
FUNCTION PROTOTYPE
double atan (double x) ;
Function
atan
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... atan of x
When x = NaN ... NaN
When x = –0 ... –0
EXPLANATION
• Calculates atan (range between –π/2 and +π/2) of x.
• When x is non-numeric, NaN is returned.
• When x is –0, –0 is returned.
• If an underflow occurs as a result of conversion, a non-normalized number is returned.
252
User’s Manual U14872EJ1V0UM
CHAPTER 10
7-4
LIBRARY FUNCTIONS
atan2 (normal model only)
Mathematical Functions
FUNCTION
atan2 finds atan of y/x.
HEADER
math.h
FUNCTION PROTOTYPE
double atan2 (double y, double x) ;
Function
atan2
Arguments
x ... Numeric value on which
operation is performed
y ... Numeric value on which
operation is performed
Return Value
Normal ... atan of y/x
When both x and y are 0 or
y/x is the value that cannot be
expressed, or either x or y is
NaN and both x and y are ± ∞
... NaN
Non-normalized number ...
When underflow occurs
EXPLANATION
• atan (range between –π and +π) of y/x is calculated. When both x and y are 0 or y/x is the value that cannot
be expressed, or when both x and y are infinite, NaN is returned and EDOM is set to errno.
• If either x or y is non-numeric, NaN is returned.
• If an underflow occurs as a result of operation, a non-normalized number is returned.
User’s Manual U14872EJ1V0UM
253
CHAPTER 10
7-5
LIBRARY FUNCTIONS
cos (normal model only)
Mathematical Functions
FUNCTION
cos finds cos.
HEADER
math.h
FUNCTION PROTOTYPE
double cos (double x) ;
Function
cos
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... cos of x
When x = NaN, x = ±∞ ... NaN
EXPLANATION
• Calculates cos of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
254
User’s Manual U14872EJ1V0UM
CHAPTER 10
7-6
LIBRARY FUNCTIONS
sin (normal model only)
Mathematical Functions
FUNCTION
sin finds sin.
HEADER
math.h
FUNCTION PROTOTYPE
double sin (double x) ;
Function
sin
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... sin of x
When x = NaN, x = ±∞ ... NaN
When underflow occurs ...
Non-normalized number
EXPLANATION
• Calculates sin of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If an underflow occurs as a result of operation, a non-normalized number is returned.
• If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
User’s Manual U14872EJ1V0UM
255
CHAPTER 10
7-7
LIBRARY FUNCTIONS
tan (normal model only)
Mathematical Functions
FUNCTION
tan finds tan.
HEADER
math.h
FUNCTION PROTOTYPE
double tan (double x) ;
Function
tan
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... tan of x
When x = NaN, x = ±∞ ... NaN
When underflow occurs ...
Non-normalized number
EXPLANATION
• Calculates tan of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If an underflow occurs as a result of operation, a non-normalized number is returned.
• If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
256
User’s Manual U14872EJ1V0UM
CHAPTER 10
7-8
LIBRARY FUNCTIONS
cosh (normal model only)
Mathematical Functions
FUNCTION
cosh finds cosh.
HEADER
math.h
FUNCTION PROTOTYPE
double cosh (double x) ;
Function
cosh
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... cosh of x
When overflow occurs, x =
NaN, x = ±∞ ... HUGE_VAL
(with positive sign)
x = NaN ... NaN
EXPLANATION
• Calculates cosh of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, a positive infinite value is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned, and ERANGE is
set to errno.
User’s Manual U14872EJ1V0UM
257
CHAPTER 10
7-9
LIBRARY FUNCTIONS
sinh (normal model only)
Mathematical Functions
FUNCTION
sinh finds sinh.
HEADER
math.h
FUNCTION PROTOTYPE
double sinh (double x) ;
Function
sinh
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... sinh of x
When x = NaN ... NaN
When x = ±∞ ... ±∞
When overflow occurs ...
HUGE_VAL (with the sign of
the overflown value)
When underflow occurs ... ±0
EXPLANATION
• Calculates sinh of x.
• If x is non-numeric, NaN is returned.
• If x is ±∞, ±∞ is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with the sign of the overflowed value is
returned, and ERANGE is set to errno.
• If an underflow occurs as a result of the operation, ±0 is returned.
258
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-10 tanh (normal model only)
Mathematical Functions
FUNCTION
tanh finds tanh.
HEADER
math.h
FUNCTION PROTOTYPE
double tanh (double x) ;
Function
tanh
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... tanh of x
When x = NaN ... NaN
When x = ±∞ ... ±1
When underflow occurs ... ±0
EXPLANATION
• Calculates tanh of x.
• If x is non-numeric, NaN is returned.
• If x is ±∞, ±1 is returned.
• If an underflow occurs as a result of the operation, ±0 is returned.
User’s Manual U14872EJ1V0UM
259
CHAPTER 10
LIBRARY FUNCTIONS
7-11 exp (normal model only)
Mathematical
FUNCTION
exp finds the exponent function.
HEADER
math.h
FUNCTION PROTOTYPE
double exp (double x) ;
Function
exp
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... exponent function of x
When x = NaN ... NaN
When x = ±∞ ... ±∞
When overflow occurs ...
HUGE_VQAL (with positive
sign)
When underflow occurs ...
Non-normalized number
When annihilation of valid
digits occurs due to underflow
... +0
EXPLANATION
• Calculates exponent function of x.
• If x is non-numeric, NaN is returned.
• If x is ±∞, ±∞ is returned.
• If an underflow occurs as a result of the operation, a non-normalized number is returned.
• If annihilation of valid digits due to underflow occurs as a result of the operation, +0 is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned and ERANGE is
set to errno.
260
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-12 frexp (normal model only)
Mathematical Functions
FUNCTION
frexp finds the mantissa and exponent part.
HEADER
math.h
FUNCTION PROTOTYPE
double frexp (double x, int *exp) ;
Function
frexp
Arguments
x ... Numeric value on which
operation is performed
exp ... Pointer to store
Return Value
Normal ... mantissa of x
When x = NaN, x = ±∞ ... NaN
When x = ±0 ... ±0
exponent part
EXPLANATION
• Divides a floating point number x by mantissa m and exponent n such as x = m*2^n and returns mantissa m.
• Exponent n is stored where the pointer exp indicates. The absolute value of m, however, is 0.5 or more and
less than 1.0.
• If x is non-numeric, NaN is returned and the value of *exp is 0.
• If x is infinite, NaN is returned, and EDOM is set to errno with the value of *exp as 0.
• If x is ±0, ±0 is returned and the value of *exp is 0.
User’s Manual U14872EJ1V0UM
261
CHAPTER 10
LIBRARY FUNCTIONS
7-13 ldexp (normal model only)
Mathematical Functions
FUNCTION
ldexp finds x*2^exp.
HEADER
math.h
FUNCTION PROTOTYPE
double ldexp (double x, int exp) ;
Function
exp
Arguments
x ... Numeric value on which
operation is performed
exp ... Exponent
Return Value
Normal ... x*2 ^ exp
When x = NaN ... NaN
When x = ±∞ ... ±∞
When x = ±0 ... ±0
When overflow occurs ...
HUGE_VAL (with the sign of
the overflown value)
When underflow occurs ...
Non-normalized number
When annihilation of valid
digits occurs due to underflow
... ±0
EXPLANATION
• Calculates x*2^exp.
• If x is non-numeric, NaN is returned.
• If x is ±∞, ±∞ is returned.
• If x is ±0, ±0 is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with the overflowed value is returned and
ERANGE is set to errno.
• If an underflow occurs as a result of the operation, a non-normalized number is returned.
• If annihilation of valid digits due to underflow occurs as a result of the operation, ±0 is returned.
262
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-14 log (normal model only)
Mathematical Functions
FUNCTION
log finds the natural logarithm.
HEADER
math.h
FUNCTION PROTOTYPE
double log (double x) ;
Function
log
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... Natural logarithm of
x
When x ≤ 0 ... HUGE_VAL
(with negative sign)
When x is non-numeric ...
NaN
When x is infinite ... +∞
EXPLANATION
• Finds the natural logarithm of x.
• If x is non-numeric, NaN is returned.
• If x is +∞, +∞ is returned.
• In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned and EDOM is set to errno.
• If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
User’s Manual U14872EJ1V0UM
263
CHAPTER 10
LIBRARY FUNCTIONS
7-15 log10 (normal model only)
Mathematical Functions
FUNCTION
log10 finds a logarithm with 10 as the base.
HEADER
math.h
FUNCTION PROTOTYPE
double log10 (double x) ;
Function
log10
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... Logarithm with 10
of x as the base
When x ≤ 0 ... HUGE_VAL
(with negative sign)
When x is non-numeric ...
NaN
When x is infinite ... +∞
EXPLANATION
• Finds a logarithm with 10 of x as the base.
• If x is non-numeric, NaN is returned.
• If x is +∞, +∞ is returned.
• In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned and EDOM is set to errno.
• If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
264
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-16 modf (normal model only)
Mathematical Functions
FUNCTION
modf finds the fraction part and integer part.
HEADER
math.h
FUNCTION PROTOTYPE
double modif (double x, double *iptr) ;
Function
modif
Arguments
x ... Numeric value on which
operation is performed
iptr ... Pointer to integer part
Return Value
Normal ... Fraction part of x
When x is non-numeric or
infinite ... NaN
When x is ±0 ... ±0
EXPLANATION
• Divides a floating point number x by a fraction part and an integer part
• Returns the fraction part with the same sign as that of x, and stores the integer part to the location indicated
by the pointer iptr.
• If x is non-numeric, NaN is returned and stored in the location indicated by the pointer iptr.
• If x is infinite, NaN is returned and stored in the location indicated by the pointer iptr, and EDOM is set to
errno.
• If x = ±0, ±0 is stored in the location indicated by the pointer iptr.
User’s Manual U14872EJ1V0UM
265
CHAPTER 10
LIBRARY FUNCTIONS
7-17 pow (normal model only)
Mathematical Functions
FUNCTION
pow finds the yth power of x.
HEADER
math.h
FUNCTION PROTOTYPE
double pow (double x, double y) ;
Function
pow
Arguments
x ... Numeric value on which
operation is performed
y ... Multiplier
Return Value
Normal ... x^y
Either when x = NaN or y =
NaN,
x = +∞ and y = 0
x < 0 and y≠ integer,
x < 0 and y = ±∞,
x = 0 and y < 0 ... NaN
When underflow occurs ...
Non-normalized number
When overflow occurs ...
HUGE_VAL (with the sign of
overflown value)
When annihilation of valid
digits occurs due to underflow
... ±0
EXPLANATION
• Calculates x^y.
• If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned,
and ERANGE is set to errno.
• When x = NaN or y = NaN, NaN is returned.
• When any of x = +∞ and y = 0, x < 0 and y ≠ integer, x < 0 and y = ±∞ or x = 0 and y ≤ 0, NaN is returned and
EDOM is set to errno.
• If an underflow occurs, a non-normalized number is returned.
• If annihilation of valid digits occurs due to underflow, ±0 is returned.
266
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-18 sqrt (normal model only)
Mathematical Functions
FUNCTION
sqrt finds the square root.
HEADER
math.h
FUNCTION PROTOTYPE
double sqrt (double x) ;
Function
sqrt
Arguments
x ... Numeric value on which
operation is performed
Return Value
When x ≥ 0 ... Square root of
x
When x = ±0 ... ±0
When x < 0 ... NaN
EXPLANATION
• Calculates the square root of x.
• In the case of an area error of x < 0, 0 is returned and EDOM is set to errno.
• If x is non-numeric, NaN is returned.
• If x is ±0, ±0 is returned.
User’s Manual U14872EJ1V0UM
267
CHAPTER 10
LIBRARY FUNCTIONS
7-19 ceil (normal model only)
Mathematical Function
FUNCTION
ceil finds the minimum integer no less than x.
HEADER
math.h
FUNCTION PROTOTYPE
double ceil (double x) ;
Function
ceil
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... The minimum
integer no less than x
When x is non-numeric or x =
±∞ ... NaN
When x = –0 ... +0
When the minimum integer no
less than x cannot be
expressed ... x
EXPLANATION
• Finds the minimum integer no less than x.
• If x is non-numeric, NaN is returned.
• If x is –0, +0 is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If the minimum integer no less than x cannot be expressed, x is returned.
268
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-20 fabs (normal model only)
Mathematical Functions
FUNCTION
fabs returns the absolute value of the floating-point number x .
HEADER
math.h
FUNCTION PROTOTYPE
double fabs (double x) ;
Function
fabs
Arguments
Return Value
x ... Numeric value to find the
Normal ... Absolute value of x
When x is non-numeric ...
NaN
When x = –0 ... +0
absolute value
EXPLANATION
• Finds the absolute value of x.
• If x is non-numeric, NaN is returned.
• If x is –0, +0 is returned.
User’s Manual U14872EJ1V0UM
269
CHAPTER 10
LIBRARY FUNCTIONS
7-21 floor (normal model only)
Mathematical Functions
FUNCTION
floor finds the maximum integer no more than x.
HEADER
math.h
FUNCTION PROTOTYPE
double floor (double x) ;
Function
floor
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... The maximum
integer no more than x
When x is non-numeric or x =
±∞ ... NaN
When x = –0 ... +0
When the maximum integer
no more than x cannot be
expressed
EXPLANATION
• Finds the maximum integer no more than x.
• If x is non-numeric, NaN is returned.
• If x is –0, +0 is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If the maximum integer no more than x cannot be expressed, x is returned.
270
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-22 fmod (normal model only)
Mathematical Functions
FUNCTION
fmod finds the remainder of x/y.
HEADER
math.h
FUNCTION PROTOTYPE
double fmod (double x, double y) ;
Function
fmod
Arguments
x ... Numeric value on which
operation is performed
y ... Numeric value on which
operation is performed
Return Value
Normal ... Remainder of x/y
When x is non-numeric or y is
non-numeric, when y is ±0,
when x is ±∞ ... NaN
When x ≠ ∞ and y = ±∞ ... x
EXPLANATION
• Calculates the remainder of x/y expressed with x – i*y. i is an integer.
• If y ≠ 0, the return value has the same sign as that of x and the absolute value is less than that of y.
• If y is ± 0 or x = ±∞, NaN is returned and EDOM is set to errno.
• If x is non-numeric or y is non-numeric, NaN is returned.
• If y is infinite, x is returned unless x is infinite.
User’s Manual U14872EJ1V0UM
271
CHAPTER 10
LIBRARY FUNCTIONS
7-23 matherr (normal model only)
Mathematical Functions
FUNCTION
matherr performs exception processing of the library that deals with floating-point numbers.
HEADER
math.h
FUNCTION PROTOTYPE
void matherr (struct exception *x) ;
Function
matherr
Arguments
struct exception {
int type;
char *name;
}
type......Numeric value to
Return Value
None
indicate arithmetic exception
name ...Function name
EXPLANATION
• When an exception occurs, matherr is automatically called in the standard library and runtime library, which
deal with floating-point numbers.
• When called from the standard library, EDOM and ERANGE are set to errno.
The following shows the relationship between the arithmetic exception type and errno.
Type
Arithmetic Exception
Value Set to errno
1
2
3
4
5
Underflow
Annihilation
Overflow
Zero division
Inoperable
ERANGE
ERANGE
ERANGE
EDOM
EDOM
Original error processing can be performed by changing or creating matherr.
272
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-24 acosf (normal model only)
Mathematical Functions
FUNCTION
acosf finds acos.
HEADER
math.h
FUNCTION PROTOTYPE
float acosf (float x) ;
Function
acosf
Arguments
x ... Numeric value on which
operation is performed
Return Value
When –1 ≤ x ≤ 1 ... acos of x
When x ≤ –1, 1 < x, x = ...
NaN
EXPLANATION
• Calculates acos (range between 0 and π) of x.
• If x is non-numeric, NaN is returned.
• In the case of a definition area error of x ≤ –1, 1 ≤ x, NaN is returned and EDOM is set to errno.
User’s Manual U14872EJ1V0UM
273
CHAPTER 10
LIBRARY FUNCTIONS
7-25 asinf (normal model only)
Mathematical Functions
FUNCTION
asinf finds asin.
HEADER
math.h
FUNCTION PROTOTYPE
float asinf (float x) ;
Function
asinf
Arguments
x ... Numeric value on which
operation is performed
Return Value
When –1 ≤ x ≤ 1 ... asin of x
When x ≤ –1, 1 < x, x = NaN
... NaN
x = –0 ... –0
When underflow occurs ...
Non-normalized number
EXPLANATION
• Calculates asin (range between –π/2 and +π/2) of x.
• If x is non-numeric, NaN is returned.
• In the case of a definition area error of x ≤ –1, 1 ≤ x, NaN is returned and EDOM is set to errno.
• If x = –0, –0 is returned.
• If an underflow occurs as a result of operation, a non-normalized number is returned.
274
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-26 atanf (normal model only)
Mathematical Functions
FUNCTION
atanf finds atan.
HEADER
math.h
FUNCTION PROTOTYPE
float atanf (float x) ;
Function
atanf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... atan of x
When x = NaN ... NaN
When x = –0 ... –0
EXPLANATION
• Calculates atan (range between –π/2 and +π/2) of x.
• If x is non-numeric, NaN is returned.
• If x = –0, –0 is returned.
• If an underflow occurs as a result of the operation, a non-normalized number is returned.
User’s Manual U14872EJ1V0UM
275
CHAPTER 10
LIBRARY FUNCTIONS
7-27 atan2f (normal model only)
Mathematical Functions
FUNCTION
atan2f finds atan of y/x.
HEADER
math.h
FUNCTION PROTOTYPE
float atan21 (float y, float x) ;
Function
atan21
Arguments
x ... Numeric value on which
operation is performed
y ... Numeric value on which
operation is performed
Return Value
Normal ... atan of y/x
When both x and y are 0 or a
value whose y/x cannot be
expressed, or either x or y is
NaN, both x and y are ±∞ ...
NaN
When underflow occurs ...
Non-normalized number
EXPLANATION
• Calculates atan (range between –π and +π) of y/x. When both x and y are 0 or the value whose y/x cannot
be expressed, or when both x and y are infinite, NaN is returned and EDOM is set to errno.
• When either x or y is non-numeric, NaN is returned.
• If an underflow occurs as a result of the operation, a non-normalized number is returned.
276
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-28 cosf (normal model only)
Mathematical Functions
FUNCTION
cosf finds cos.
HEADER
math.h
FUNCTION PROTOTYPE
float cost (float x) ;
Function
cosf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... cos of x
When x = NaN, x = ±∞ ... NaN
EXPLANATION
• Calculates cos of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
User’s Manual U14872EJ1V0UM
277
CHAPTER 10
LIBRARY FUNCTIONS
7-29 sinf (normal model only)
Mathematical Functions
FUNCTION
sinf finds sin.
HEADER
math.h
FUNCTION PROTOTYPE
float sinf (float x) ;
Function
sinf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... sin of x
When x = NaN, x = ±∞ ... NaN
When underflow occurs ...
Non-normalized number
EXPLANATION
• Calculates sin of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If an underflow occurs as a result of the operation, a non-normalized number is returned.
• If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
278
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-30 tanf (normal model only)
Mathematical Functions
FUNCTION
tanf finds tan.
HEADER
math.h
FUNCTION PROTOTYPE
float tanf (float x) ;
Function
tanf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... tan of x
When x = NaN, x = ±∞ ... NaN
When underflow occurs ...
Non-normalized number
EXPLANATION
• Calculates tan of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If an underflow occurs as a result of operation, a non-normalized number is returned.
• If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
User’s Manual U14872EJ1V0UM
279
CHAPTER 10
LIBRARY FUNCTIONS
7-31 coshf (normal model only)
Mathematical Functions
FUNCTION
coshf finds cosh.
HEADER
math.h
FUNCTION PROTOTYPE
float coshf (float x) ;
Function
coshf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... cosh of x
When overflow occurs, x = ±∞
... HUGE_VAL (with a positive
sign)
x = NaN ... NaN
EXPLANATION
• Calculates cosh of x.
• If x is non-numeric, NaN is returned.
• If x is infinite, positive infinite value is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned and ERANGE is
set to errno.
280
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-32 sinhf (normal model only)
Mathematical Functions
FUNCTION
sinhf finds sinh.
HEADER
math.h
FUNCTION PROTOTYPE
float sinhf (float x) ;
Function
sinhf
Arguments
Return Value
x ... Numeric value on which
Normal ... sinh of x
operation is performed
When overflow occurs ...
HUGE_VAL (with a sign of the
overflown value)
x = NaN ... NaN
When x = ±∞ ... ±∞
When underflow occurs ... ±0
EXPLANATION
• Calculates sinh of x.
• If x is non-numeric, NaN is returned.
• If x is ±∞, ±∞ is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned
and ERANGE is set to errno.
• If an underflow occurs as a result of the operation, ±0 is returned.
User’s Manual U14872EJ1V0UM
281
CHAPTER 10
LIBRARY FUNCTIONS
7-33 tanhf (normal model only)
Mathematical Functions
FUNCTION
tanhf finds tanh.
HEADER
math.h
FUNCTION PROTOTYPE
float tanhf (float x) ;
Function
tanhf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... tanh of x
x = NaN ... NaN
When x = ±∞ ... ±1
When underflow occurs ... ±0
EXPLANATION
• Calculates tanh of x.
• If x is non-numeric, NaN is returned.
• If x is ±∞, ±1 is returned.
• If an underflow occurs as a result of the operation, ±0 is returned.
282
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-34 expf (normal model only)
Mathematical Functions
FUNCTION
expf finds the exponent function.
HEADER
math.h
FUNCTION PROTOTYPE
float expf (float x) ;
Function
expf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... Exponent function of
x
When overflow occurs ...
HUGE_VAL (with positive sign)
x = NaN ... NaN
When x = ±∞ ... ±∞
When underflow occurs ...
Non-normalized number
When annihilation of effective
digits occurs due to underflow
... +0
EXPLANATION
• Calculates the exponent function of x.
• If x is non-numeric, NaN is returned.
• If x is ±∞, ±∞ is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned and ERANGE is
set to errno.
• If an underflow occurs as a result of the operation, a non-normalized number is returned.
• If annihilation of valid digits occurs due to underflow as a result of the operation, +0 is returned.
User’s Manual U14872EJ1V0UM
283
CHAPTER 10
LIBRARY FUNCTIONS
7-35 frexpf (normal model only)
Mathematical Functions
FUNCTION
frexpf finds the mantissa and exponent parts.
HEADER
math.h
FUNCTION PROTOTYPE
float frexpf (float x, int *exp) ;
Function
frexpf
Arguments
x ... Numeric value on which
operation is performed
exp ... Pointer to store exponent
Return Value
Normal ... Mantissa of x
When x = NaN, x = ±∞ ... NaN
When x = ±0 ... ±0
part
EXPLANATION
• Divides a floating-point number x by mantissa m and exponent n such as x = m*2^n and returns mantissa m.
• Exponent n is stored where the pointer exp indicates. The absolute value of m, however, is 0.5 or more and
less than 1.0.
• If x is non-numeric, NaN is returned and the value of *exp is 0.
• If x is ±∞, NaN is returned, and EDOM is set to errno with the value of *exp as 0.
• If x is ±0, ±0 is returned and the value of *exp is 0.
284
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-36 ldexpf (normal model only)
Mathematical Functions
FUNCTION
ldexpf finds x*2^exp.
HEADER
math.h
FUNCTION PROTOTYPE
float ldexpf (float x, int exp) ;
Function
ldexpf
Arguments
x ... Numeric value on which
operation is performed
exp ... Exponent
Return Value
Normal ... x*2^exp
When x = NaN ... NaN
When x = ±∞ ... ±∞
When x = ±0 ... ±0
When overflow occurs ...
HUGE_VAL (with the sign of
overflown value)
When underflow occurs ...
Non-normalized numberV
When annihilation of valid
digits occurs due to underflow
... ±0
EXPLANATION
• Calculates x*2^exp.
• If x is non-numeric, NaN is returned. If x is ±∞, ±∞ is returned. If x is ±0, ±0 is returned.
• If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned
and ERANGE is set to errno.
• If an underflow occurs as a result of the operation, a non-normalized number is returned .
• If annihilation of valid digits due to underflow occurs as a result of the operation, ±0 is returned.
User’s Manual U14872EJ1V0UM
285
CHAPTER 10
LIBRARY FUNCTIONS
7-37 logf (normal model only)
Mathematical Functions
FUNCTION
logf finds the natural logarithm.
HEADER
math.h
FUNCTION PROTOTYPE
float logf (float x) ;
Function
logf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... Natural logarithm of x
When x is non-numeric ... NaN
When x is infinite ... +∞
When x ≤ 0 ... HUGE_VAL
(with negative sign)
EXPLANATION
• Finds the natural logarithm of x.
• If x is non-numeric, NaN is returned.
• If x is +∞, +∞ is returned.
• In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned, and EDOM is set to errno.
• If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
286
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-38 log10f (normal model only)
Mathematical Functions
FUNCTION
log10f finds a logarithm with 10 as the base.
HEADER
math.h
FUNCTION PROTOTYPE
float log10f (float x) ;
Function
log10f
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... Logarithm with 10 of
x as the base
When x is non-numeric ... NaN
When x = +∞ ... +∞
When x ≤ 0 ... HUGE_VAL
(with negative sign)
EXPLANATION
• Finds a logarithm with 10 of x as the base.
• If x is non-numeric, NaN is returned.
• If x is +∞, +∞ is returned.
• In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned, and EDOM is set to errno.
• If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
User’s Manual U14872EJ1V0UM
287
CHAPTER 10
LIBRARY FUNCTIONS
7-39 modff (normal model only)
Mathematical Functions
FUNCTION
modff finds the fraction part and integer part.
HEADER
math.h
FUNCTION PROTOTYPE
float modff (float x, float *iptr) ;
Function
modff
Arguments
x ... Numeric value on which
operation is performed
iptr ... Pointer for integer part
Return Value
Normal ... Fraction part of x
When x is non-numeric or
infinite ... NaN
When x = ±0 ... ±0
EXPLANATION
• Divides a floating point number x by the fraction part and integer part.
• Returns the fraction part with the same sign as that of x, and stores the integer part in the location indicated
by the pointer iptr.
• If x is non-numeric, NaN is returned and stored in the location indicated by the pointer iptr.
• If x is infinite, NaN is returned and stored in the location indicated by the pointer iptr, and EDOM is set to
errno.
• If x = ±0, ±0 is returned and stored in the location indicated by the pointer iptr.
288
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-40 powf (normal model only)
Mathematical Functions
FUNCTION
powf finds the yth power of x.
HEADER
math.h
FUNCTION PROTOTYPE
float powf (float x, float y) ;
Function
powf
Arguments
Return Value
x ... Numeric value on which
Normal ... x^y
operation is performed
y ... Multiplier
Either when =
x = NaN or y = NaN
x = +∞ and y = 0
x < 0 and y≠ integer,
x < 0 and y = ±∞
x = 0 and y≠ 0 ... NaN
When underflow occurs ...
Non-normalized number
When overflow occurs ...
HUGE_VAL (with the sign of
overflown value)
When annihilation of valid
digits occurs due to underflow
... ±0
EXPLANATION
• Calculates x^y.
• If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned,
and ERANGE is set to errno.
• When x = NaN or y = NaN, NaN is returned.
• When any of x = +∞ and y = 0, x < 0 and y ≠ integer, x < 0 and y = ±∞, or x = 0 and y ≤ 0, NaN is returned
and EDOM is set to errno.
• If an underflow occurs, a non-normalized number is returned.
• If annihilation of valid digits occurs due to underflow, ±0 is returned.
User’s Manual U14872EJ1V0UM
289
CHAPTER 10
LIBRARY FUNCTIONS
7-41 sqrtf (normal model only)
Mathematical Functions
FUNCTION
sqrtf finds the square root.
HEADER
math.h
FUNCTION PROTOTYPE
float sqrtf (float x) ;
Function
sqrtf
Arguments
x ... Numeric value on which
operation is performed
Return Value
When x ≥ 0 ... Square root of x
When x = ±0 ... ±0
When x < 0 ... NaN
EXPLANATION
• Calculates the square root of x.
• In the case of area error of x < 0, 0 is returned and EDOM is set to errno.
• If x is non-numeric, NaN is returned.
• If x is ±0, ±0 is returned.
290
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-42 ceilf (normal model only)
Mathematical Functions
FUNCTION
ceilf finds the minimum integer no less than x.
HEADER
math.h
FUNCTION PROTOTYPE
float ceilf (float x) ;
Function
ceilf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... The minimum
integer no less than x
When x is non-numeric or x =
±∞ ... NaN
When x = –0 ... +0
When the minimum integer no
less than x cannot be
expressed ... x
EXPLANATION
• Finds the minimum integer no less than x.
• If x is non-numeric, NaN is returned.
• If x is –0, +0 is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If the minimum integer no less than x cannot be expressed, x is returned.
User’s Manual U14872EJ1V0UM
291
CHAPTER 10
LIBRARY FUNCTIONS
7-43 fabsf (normal model only)
Mathematical Functions
FUNCTION
fabsf returns the absolute value of the floating point number x.
HEADER
math.h
FUNCTION PROTOTYPE
float fabsf (float x) ;
Function
fabsf
Arguments
Return Value
x ... Numeric value to find the
Normal ... Absolute value of x
When x is non-numeric ... NaN
When x = –0 ... +0
absolute value
EXPLANATION
• Finds the absolute value of x.
• If x is non-numeric, NaN is returned.
• If x is –0, +0 is returned.
292
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-44 floorf (normal model only)
Mathematical Functions
FUNCTION
floorf finds the maximum integer no more than x.
HEADER
math.h
FUNCTION PROTOTYPE
float floorf (float x) ;
Function
floorf
Arguments
x ... Numeric value on which
operation is performed
Return Value
Normal ... The maximum
integer no more than x
When x is non-numeric or
infinite ... NaN
When x = –0 ... +0
When the maximum integer no
more than x cannot be
expressed ... x
EXPLANATION
• Finds the maximum integer no more than x.
• If x is non-numeric, NaN is returned.
• If x is –0, +0 is returned.
• If x is infinite, NaN is returned and EDOM is set to errno.
• If the maximum integer no more than x cannot be expressed, x is returned.
User’s Manual U14872EJ1V0UM
293
CHAPTER 10
LIBRARY FUNCTIONS
7-45 fmodf (normal model only)
Mathematical Functions
FUNCTION
fmodf finds the remainder of x/y.
HEADER
math.h
FUNCTION PROTOTYPE
float fmodf (float x, float y) ;
Function
fmodf
Arguments
x ... Numeric value on which
operation is performed
y ... Numeric value on which
operation is performed
Return Value
Normal ... Remainder of x/y
When x is non-numeric or y is
non-numeric
When y is ±0, when x is ±∞ ...
NaN
When x ≠ ∞ and y = ±∞ ... x
EXPLANATION
• Calculates the remainder of x/y expressed with x – i*y. i is an integer.
• If y ≠ 0, the return value has the same sign as that of x and the absolute value is less than y.
• If y is ± 0 or x = ±∞, NaN is returned and EDOM is set to errno.
• If x is non-numeric or y is non-numeric, NaN is returned.
• If y is infinite, x is returned unless x is infinite.
294
User’s Manual U14872EJ1V0UM
CHAPTER 10
8-1
LIBRARY FUNCTIONS
_ _assertfail (normal model only)
Diagnostic Functions
FUNCTION
_ _assertfail supports the assert macro.
HEADER
math.h
FUNCTION PROTOTYPE
int _ _assertfail (char*_ _msg, char*_ _cond, char*_ _file, int_ _line) ;
Function
_ _assertfail
Arguments
_ _msg ... Pointer to character
Return Value
Undefined
string to indicate output
conversion specification to be
passed to printf function
_ _cond ... Actual argument of
assert macro
_ _file ... Source file name
_ _line ... Source line number
EXPLANATION
• The _ _assertfail function receives information from the assert macro (refer to 10.2 Headers (13) assert.h),
calls the printf function, outputs information, and calls the abort function.
• The assert macro adds diagnostic functions to a program. When the assert macro is executed, if p is false
(equal to 0), the assert macro passes information related to the specific call that has brought the false value
(actual argument text, source file name, and source line number are included in the information. The other
two are the values of macro _ _FILE_ _ and _ _LINE_ _) to the _ _assertfail function.
User’s Manual U14872EJ1V0UM
295
CHAPTER 10
LIBRARY FUNCTIONS
10.5 Batch Files for Update of Startup Routine and Library Functions
This compiler is provided with batch files for updating a part of the standard library functions and the startup
routine. The batch files in the BAT directory are shown in Table 10-12 below.
Caution
The file d9026.78k in the BAT directory is used during batch file activation for updating the
library, not for development. When developing a system, it is necessary to have a device file
(sold separately).
Table 10-12. Batch Files for Updating Library Functions
Batch File
Application
mkstup.bat
Updates the startup routine (cstart[n].asm).
When changing the startup routine, perform assembly using this batch file.
reprom.bat
Updates the firmware ROM termination routine (rom.asm).
When changing rom.asm, update the library using this batch file.
repgetc.bat
Updates the getchar function.
The default assumption sets P0 of the SFR to input port. When it is necessary to change this setting, change
the defined value of EQU of PORT in getchar.asm and update the library using this batch file.
repputc.bat
Updates the putchar function.
The default assumption sets P0 of the SFR to output port. When it is necessary to change this setting,
change the defined value of EQU of PORT in putchar.asm and update the library using this batch file.
repputcs.bat
Updates the putchar function to SM78K0S-supporting.
When it is necessary to check the output of the putchar function using the SM78K0S, update the library using
this batch file.
repselo.bat
Saves/restores the reserved area of the compiler ([email protected]) as part of the save/restore processing of the
setjmp/longjmp functions (the default assumption is to not save/restore). Update the library using this batch
file when the -QR option is specified.
repselon.bat
Does not save/restore the reserved area of the compiler ([email protected]) as part of the save/restore processing
of the setjmp/longjmp functions (the default assumption is to not save/restore). Update the library using this
batch file when the -QR option is not specified.
296
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
10.5.1 Using batch files
Use the batch files in the subdirectory BAT. Because these files are the batch files used to activate the assembler
and librarian, an environment in which the assembler package RA78K0S Ver.1.30 or later operates is necessary.
Before using the batch files, set the directory that contains the RA78K0S execution format file using the environment
variable PATH.
Create a subdirectory (LIB) of the same level as BAT for the batch files and put the post-assembly files in this
subdirectory. When a C startup routine or library is installed in a subdirectory LIB that is the same level as BAT,
these files are overwritten.
To use the batch files, move the current directory to the subdirectory BAT and execute each batch file. At this
time, the following parameters are necessary.
Product type = chiptype (classification of target chip)
9026 ··· µPD789026, etc.
The following is an illustration of how to use each batch file.
The batch file for:
(1) Startup routine
• For PC-9800 series, IBM PC/AT and compatibles
mkstup chiptype
Example mkstup
9026
• For HP9000 series 700™, SPARCstation™ Family
/bin/sh mkstup.sh chiptype
Example /bin/sh
mkstup.sh
9026
(2) Firmware ROM routine update
• For PC-9800 series, IBM PC/AT and compatibles
reprom chiptype
Example reprom
9026
• For HP9000 series 700, SPARCstation Family
/bin/sh reprom.sh chiptype
Example /bin/sh
reprom.sh
9026
User’s Manual U14872EJ1V0UM
297
CHAPTER 10
LIBRARY FUNCTIONS
(3) getchar function update
• For PC-9800 series, IBM PC/AT and compatibles
repgetc chiptype
Example repgetc
9026
• For HP9000 series 700, SPARCstation Family
/bin/sh repgetc.sh chiptype
Example /bin/sh
repgetc.sh
9026
(4) putchar function update
• For PC-9800 series, IBM PC/AT and compatibles
repputc chiptype
Example repputc
9026
• For HP9000 series 700, SPARCstation Family
/bin/sh repputc.sh chiptype
Example /bin/sh
repputc.sh
9026
(5) putchar function (SM78K0S-supporting) update
• For PC-9800 series, IBM PC/AT and compatibles
repputcs chiptype
Example repputcs
9026
• For HP9000 series 700, SPARCstation Family
/bin/sh repputcs.sh chiptype
Example /bin/sh
298
repputcs.sh
9026
User’s Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(6) setjmp/longjmp function update (with restore/save processing)
• For PC-9800 series, IBM PC/AT and compatibles
repselo chiptype
Example repselo
9026
• For HP9000 series 700, SPARCstation Family
/bin/sh repselo.sh chiptype
Example /bin/sh
repselo.sh
9026
(7) setjmp/longjmp function update (without restore/save processing)
• For PC-9800 series, IBM PC/AT and compatibles
repselon chiptype
Example repselon
9026
• For HP9000 series 700, SPARCstation Family
/bin/sh repselon.sh chiptype
Example /bin/sh
repselon.sh
9026
User’s Manual U14872EJ1V0UM
299
CHAPTER 11
EXTENDED FUNCTIONS
This chapter describes the extended functions unique to this C compiler and not specified in the ANSI (American
National Standards Institute) Standard for C.
The extended functions of this C compiler are used to generate codes for effective utilization of the target devices
in the 78K/0S Series. Not all of these extended functions are always effective. Therefore, it is recommended to use
only the effective ones according to the user’s purpose. For the effective use of the extended functions, refer to
CHAPTER 13 EFFECTIVE UTILIZATION OF COMPILER along with this chapter.
C source programs created by using the extended functions of the C compiler utilize microcontroller-dependent
functions. As regards portability to other microcontrollers, they are compatible at the C language level. For this
reason, C source programs developed by using these extended functions are portable to other microcontrollers with
easy-to-make modifications.
Remark
300
In the explanation of this chapter, “RTOS” stands for the 78K/0 Series real-time OS.
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.1 Macro Names
This C compiler has two types of macro names: those indicating the series names for target devices and those
indicating device names (processor types). These macro names are specified according to the option at compilation
to output object code for a specific target device or according to the processor type in the C source. In the example
below, _ _K0S_ _ and _ _9026_ are specified.
For details of these macro names, see 9.8 Predefined Macro Names.
[Example]
Compile option
>CC78K0S
-C9026
prime.c …
Specification of device type:
#pragma pc (9026)
User’s Manual U14872EJ1V0UM
301
CHAPTER 11
EXTENDED FUNCTIONS
11.2 Keywords
The following tokens have been added to this C compiler as keywords to realize the extended functions. As with
ANSI-C keywords, these tokens cannot be used as labels or variable names. All the keywords must be described in
lowercase letters. A keyword containing uppercase letters, is not interpreted as such by the C compiler.
The following shows the list of keywords added to this compiler. Of these keywords, ones not starting with “_ _”
can be disabled by specifying the option (-ZA) that enables only ANSI-C language specifications (for the ANSI-C
keywords, refer to 2.2 Keywords).
Table 11-1. List of Added Keywords
Keyword
Use
_ _callt
callt
callt/_
_ _callt functions
_ _callf
callf
callf/_
_ _callf functions
_ _sreg
sreg
sreg/_
_ _sreg variables
noauto
noauto functions
_ _leaf
norec
norec/_
_ _leaf functions
_ _boolean
boolean
boolean type/_
_ _boolean type variables
bit
bit type variables
Note
_ _interrupt
Hardware interrupt
_ _interrupt_
_brk
Note
Software interrupt
_ _banked 1 to 15
Bank function
_ _asm
ASM statements
Note
_ _rtos_
_interrupt
Handler to allocate for RTOS
_ _pascal
Pascal function
_ _directmap
Absolute address allocation specification
_ _temp
Temporary variable
Note
Note A warning is output for the descriptions callf, _ _callf, _ _interrupt_brk, _ _banked 1 to 15, and
_ _rtos_interrupt and they are ignored.
(1) Functions
The keywords callt, _ _callt, noauto, norec, _ _leaf, _ _interrupt, and _ _pascal are attribute qualifiers.
These keywords must be described before any function declaration. The format of each attribute qualifier is
shown below.
attribute qualifier ordinary declarator function name (parameter type list/identifier list)
[Example]
_ _callt
int
func (int);
Attribute qualifier specifications are limited to those listed below. (The noauto and norec/_ _leaf qualifiers
cannot be specified at the same time.) callt and _ _callt, callf and _ _callf, norec and _ _leaf are regarded as
the same specifications. However, the qualifiers with ‘_ _’ added are enabled even when the -ZA option is
specified.
302
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
• callt
• noauto
• norec
• callt noauto
• callt norec
• noauto callt
• norec callt
• _ _interrupt
• _ _pascal
• _ _pascal noauto
• _ _pascal callt
• noauto _ _pascal
• callt _ _pascal
• callt noauto _ _pascal
(2) Variables
• The same regulations apply to the sreg or _ _sreg specification as to register in C language (refer to 11.5 (3)
How to use the saddr area for details).
• The same regulations apply to the bit, boolean or _ _boolean specification as to the char or int type
specifier in C language.
However, these types can be specified only for the variables defined outside a function (external variables).
• The same regulations apply to the _ _directmap specification as to the type qualifier in C language (refer to
11.5 (31) Absolute address allocation specification for details).
• The same regulations apply to the _ _temp specification as to the type qualifier in C language (refer to 11.5
(33) Temporary variables for details).
User’s Manual U14872EJ1V0UM
303
CHAPTER 11
EXTENDED FUNCTIONS
11.3 Memory
The memory model is determined by the memory space of the target device.
(1) Memory model
Since memory space is a maximum of 64 KB, the model is 64 KB with code division and data division combined.
(2) Register bank
There is no register bank.
(3) Memory space
This C compiler uses memory space as shown below.
304
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Table 11-2. Utilization of Memory Space
(a) Normal model (default)
Address
Use
Size (bytes)
00
40 to 7FH
CALLT table
64
FE
20 to D7H
sreg variables, boolean type variables
184
FE
D8 to E7H
Register variablesNote 1
16
FE
E8 to EFH
Arguments of norec functionsNote 2
8
FE
F0 to F7H
Automatic variables of norec functionsNote 3
8
FE
F8 to FFH
Arguments of runtime libraryNote 4
8
FF
00 to FFH
sfr variables
256
(b) Static model (at -SM16 specification)
Address
Use
Size (bytes)
00
40 to 7FH
CALLT table
64
FE
20 to EFH
sreg variables, boolean type variables
208
FE
F0 to FFH
Shared areaNote 5
16
FE
Consecutive
areas
between 20
and FFH
For arguments, automatic variables, and workNote 6
8
FF
00 to FFH
sfr variables
256
Notes 1. Area not used for register variables is used for sreg variables and boolean type variables.
2. If not completely used for register variables, area not used for norec function arguments is used for sreg
variables and boolean type variables.
3. If not completely used for register variables and norec function arguments, area not used for norec
function automatic variables is used for sreg variables and boolean type variables.
4. If not completely used for register variables and norec function arguments/automatic variables, area not
used for runtime library arguments is used for sreg variables and boolean type variables.
5. The area used by the compiler varies depending on the parameters of the –SM option. Area not used as
shared area is used for sreg variables and boolean type variables.
6. Valid only when the static model expansion specification option (-ZM) is specified.
Remark
If the register variable optimization option (-QR) is not specified, the area in Notes 1 to 3 is always used for
sreg variables and boolean type variables.
User’s Manual U14872EJ1V0UM
305
CHAPTER 11
EXTENDED FUNCTIONS
11.4 #pragma Directive
The #pragma directive is one of the preprocessing directives supported by ANSI.
The #pragma directive,
depending on the character string to follow #pragma, instructs the compiler to translate using the method determined
by the compiler. If the compiler does not support the #pragma directive, the #pragma directive is ignored and
compilation is continued. If keywords are added by the directive, an error is output if the C source includes the
keywords. In order to avoid this, the keywords in the C source should either be deleted or sorted by the #ifdef
directive.
This C compiler supports the following #pragma directives to realize the extended functions.
The keywords specified after #pragma can be described either in uppercase or lowercase letters.
For the extended functions using #pragma directives, refer to 11.5 How to Use Extended Functions.
306
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Table 11-3. List of #pragma Directives
#pragma Directive
Applications
#pragma sfr
Describes SFR name in C → 11.5 (4) How to use the sfr area
#pragma asm
Inserts ASM statement in C source → 11.5 (8) ASM statements
#pragma vect
#pragma interrupt
Describes interrupt processing in C → 11.5 (9) Interrupt functions
#pragma di
#pragma ei
Describes DI/EI instructions in C → 11.5 (11) Interrupt functions
#pragma halt
#pragma stop
#pragma nop
Describes CPU control instructions in C → 11.5 (12) CPU control instruction
#pragma access
Uses absolute address access functions → 11.5 (13) Absolute address access function
#pragma section
Changes compiler output section name and specifies section location
→ 11.5 (15) Changing compiler output section name
#pragma name
Changes module name → 11.5 (17) Module name changing function
#pragma rot
Uses rotate function → 11.5 (18) Rotate function
#pragma mul
Uses multiplication function → 11.5 (19) Multiplication function
#pragma div
Uses division function → 11.5 (20) Division function
#pragma bcd
Uses BCD operation function → 11.5 (21) BCD operation function
#pragma opc
Uses data insertion function → 11.5 (22) Data insertion function
#pragma realregister
Uses register direct reference function → 11.5 (29) Register direct reference function
#pragma inline
Expands the standard library functions memcpy and memset inline
→ 11.5 (30) Memory manipulation function
User’s Manual U14872EJ1V0UM
307
CHAPTER 11
EXTENDED FUNCTIONS
11.5 How to Use Extended Functions
This section describes each of these extended functions in the following format.
FUNCTION:
Outlines the function that can be implemented with the extended function.
EFFECT:
Explains the effect brought about by the extended function.
USAGE:
Explains how to use the extended function.
EXAMPLE:
Indicates an application example of the extended function.
RESTRICTIONS:
Explains restrictions, if any, on the use of the extended function.
EXPLANATION:
Explains the above application example.
COMPATIBILITY:
Explains the compatibility of a C source program developed by another C compiler when it is to be compiled with
this C compiler.
308
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(1) callt functions
callt/_
_ _callt
callt Functions
FUNCTION
• The callt instruction stores the address of a function to be called in an area [40H to 7FH] called the callt
table, so that the function can be called with a shorter code than the one used to call the function directly.
• To call a function declared by the callt (or _ _ callt) (called the callt function), a name with ? prefixed to the
function name is used. To call the function, the callt instruction is used.
• The function to be called does not differ from an ordinary function.
EFFECT
The object code can be shortened.
USAGE
Add the callt/_ _ callt attribute to the function to be called as follows (described at the beginning).
callt extern
type-name
function-name
_ _callt extern type-name function-name
EXAMPLE
_ _callt void func1 (void) ;
_ _callt void func1 (void) {
.
.
.
/* function body */
.
.
.
}
User’s Manual U14872EJ1V0UM
309
CHAPTER 11
EXTENDED FUNCTIONS
callt/_
_ _callt
callt Functions
RESTRICTIONS
• The address of each function declared with callt/_ _ callt will be allocated to the callt table when object
modules are linked. For this reason, when using the callt table in an assembler source module, the routine to
be created must be made “relocatable” using symbols.
• A check on the number of callt functions is made at linking.
• When the -ZA option is specified, _ _callt is enabled and callt is disabled.
• The area of the callt table is 40H to 7FH.
• When the callt table is used exceeding the number of permitted callt attribute functions, a compile error will
occur.
• The callt table is used by specifying the -QL option. For that reason, the number of callt attributes permitted
per load module and the total in the linking modules is as shown in Table 11-4.
• When the option for using the library that supports prologue/epilogue (-ZD option) is specified, the -QL4
option cannot be used. Also, because two callt entries are used by the library that supports prologue/epilogue
in the case of a normal model and up to ten in the case of a static model, the maximum number of callt
entries is reduced by two in the case of a normal model and by up to ten in the case of a static model.
Table 11-4. The Number of callt Attribute Functions That Can Be Used When the -QL Option Is Specified
• When QQ option is not specified simultaneously
Option
-QL1
-QL2
-QL3
-QL4
Normal model
30
27
13
0
Static model
30
29
15
12
-QL1
-QL2
-QL3
-QL4
Normal model
30
27
18
11
Static model
30
29
20
13
• When QQ option is specified simultaneously
Option
• Cases where the -QL option is not used and the defaults are as shown below.
Table 11-5. Restrictions on callt Function Usage
callt Function
Restriction Value
Number per load module
30 max.
Total number in linked module
30 max.
310
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
EXAMPLE
(C source)
============ ca1.c ============
============ ca2.c ============
_ _callt extern int tsub ( );
void main ( )
_ _callt int tsub ( )
{
{
int ret_val;
int val;
ret_val = tsub ( );
}
return val;
}
(Output object of compiler)
ca1 module
EXTRN
?tsub
; Declaration
callt
[?tsub]
; Call
PUBLIC
_tsub
; Declaration
PUBLIC
?tsub
;
@@CALT CSEG
CALLT0
; Allocation to segment
?tsub: DW
_tsub
ca2 module
@@CODE CSEG
; Function definition
_tsub:
.
.
.
function body
.
.
.
EXPLANATION
• The callt attribute is given to the function tsub() so that it can be stored in the callt table.
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if the keyword callt/_ _ callt is not used.
• To change functions to callt functions, observe the procedure described in the USAGE above.
<From this C compiler to another C compiler>
• #define must be used. For details, see 11.6 Modifications of C Source.
User’s Manual U14872EJ1V0UM
311
CHAPTER 11
EXTENDED FUNCTIONS
(2) Register variables
Register Variables
register
FUNCTION
• Allocates the declared variables (including arguments of function) to the register (HL) and saddr area
([email protected] to [email protected]).
Saves and restores registers or saddr area during the preprocessing/
postprocessing of the module that declared a register.
• The allocation is performed based on the number of times referenced. Therefore, it is undetermined to which
register or saddr area the register variable is allocated.
• For details of register variable allocation, refer to 11.7 Function Call Interface.
• Register variables are allocated to different areas depending on the compile condition as shown below (for
each option, refer to the CC78K0S C Compiler Operation (U14871E)).
1. In the case of the normal model, the register variables are allocated based on the number of times
referenced to register HL or the saddr area [FED0H to FEDFH]. If there is no stack frame, register
variables are allocated to register HL.
Only when the -QR option is specified, register variables are
allocated to the saddr area.
2. In the case of the static model, the register variables are allocated to register DE or [email protected] secured
by -SM specification according to the number of times referenced. Only when the -ZM2 option is specified,
register variables are allocated to the [email protected] For details of the -ZM2 option, refer to 11.5 (32) Static
model expansion specifications.
EFFECT
• Instructions to the variables allocated to the registers or saddr area are generally shorter in code length than
those to memory. This helps shorten object code and also improves program execution speed.
USAGE
Declare a variable with the register storage class specifier as follows.
register type-name variable-name
EXAMPLE
void main (void) {
register unsigned char c ;
.
.
.
}
312
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Register Variables
register
RESTRICTIONS
• If register variables are not used so frequently, object code may increase (depending on the size and contents
of the source).
• Register variable declarations may be used for char/int/short/long/float/double/long double and pointer
data types.
(Normal model)
• char uses half the area of other types. long/float/double/long double use twice the area. Between char
types there are byte boundaries but in other cases, there are word boundaries.
• In the case of int/short and pointers, a maximum of 8 variables per function is usable. From the 9th variable,
the register variables are assigned to the normal memory.
• In the case of a function without a stack frame, a maximum of 8 variables per function is usable for int/short
and pointers. From the 9th variable, the register variables are assigned to the normal memory.
(Static model)
• char uses half the area of other types.
• In the case of int/short and pointers, a maximum of 1 variable per function is usable.
• From the 2nd variable, the register variables are assigned to the normal memory.
• The register variables are invalid for long/float/double/long double.
Table 11-6. Restrictions on Register Variable Usage
Data Type
int/short
Pointer
Usable Number (per Function)
Normal Model
Static Model
8 variables max.
1 variable max.
8 variables max.
(9 variables max. if function without stack frame)
User’s Manual U14872EJ1V0UM
1 variable max.
313
CHAPTER 11
EXTENDED FUNCTIONS
Register Variables
register
EXAMPLE
(C source)
void func ();
void main ()
{
register int i, j;
i = 0;
j = 1;
i += j;
func ();
}
(Output object of compiler)
• When the -SM option is not specified (example of register variable allocation to register HL and the saddr
area)
The following labels are declared by the startup routine (refer to APPENDIX A LIST OF LABELS FOR saddr
AREA).
[email protected]
; References the saddr area to be used
push
hl
; Saves the contents of the register at the beginning of the function
movw
ax, [email protected]
; Saves the contents of the saddr at the beginning of the function
push
ax
;
movw
hl, #00H
; The following codes are output in the middle of the function
movw
ax, hl
;
incw
ax
;
movw
[email protected],ax
;
xch
a, x
;
add
a, l
;
xch
a, x
;
addc
a, l
;
movw
hl, ax
;
call
!_func
;
pop
ax
; Restores contents of the saddr at the end of the function
movw
[email protected], ax
;
pop
hl
; Restores contents of the register at the end of the function
EXTRN
_main:
ret
314
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Register Variables
register
• When the -SM option is specified (Example of register variable allocation to register DE)
_main:
push
de
; Saves the contents of the register at the beginning of the function
movw
de, #00H; 0
;
movw
de, ax
;
incw
ax
;
movw
!?L0003+1, a
;
xch
a, x
;
mov
!?L0003, a
;
add
a, e
;
xch
a, x
;
addc
a, d
;
mov
de, ax
;
call
!_func
pop
de
; Restores the contents of the register at the end of the function
ret
EXPLANATION
• To use register variables, you only need to declare them with the register storage class specifier.
• Labels such as [email protected] include the modules declared with PUBLIC in the library attached to this C
compiler.
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if the other C compiler supports register declarations.
• To change to register variables, add the register declarations for the variables to the program.
<From this C compiler to another C compiler>
• The C source program need not be modified if the other compiler supports register declarations.
• How many variable registers can be used and to which area they will be allocated depends on the
implementations of the other C compiler.
User’s Manual U14872EJ1V0UM
315
CHAPTER 11
EXTENDED FUNCTIONS
(3) How to use the saddr area
Usage of saddr Area
sreg/_ _sreg
(1) Usage with sreg declaration
FUNCTION
• The external variables and in-function static variables (called sreg variables) declared with the keyword sreg
or _ _sreg are automatically allocated to the saddr area [FE20H to FED7H] (normal model) and [FE20H to
FEEFH] (static model) with relocatability. When those variables exceed the area shown above, a compile
error occurs.
• The sreg variables are treated in the same manner as the ordinary variables in the C source.
• Each bit of sreg variables of char, short, int, and long type become boolean type variables automatically.
• sreg variables declared without an initial value take 0 as the initial value.
• The area that can be referenced by the sreg variables declared in the assembler source is the saddr area
[FE20H to FEFFH]. The area [FED8H to FEFFH] (normal model) and [FEF0H to FEFFH] (static model) are
used by compiler, so care must be taken (refer to Table 11-2 Utilization of Memory Space).
EFFECT
• Instructions to the saddr area are generally shorter in code length than those to memory. This helps shorten
object code and also improves program execution speed.
USAGE
• Declare variables with the keywords sreg and _ _sreg inside a module and a function which defines the
variables. Only variables with a static storage class specifier can become sreg variables inside a function.
sreg type-name variable-name / sreg static type-name variable-name
_ _sreg type-name variable-name / _ _sreg static type-name variable-name
• Declare the following variables inside a module that refers to sreg external variables. They can be described
inside a function as well.
extern sreg type-name variable-name / extern _ _sreg type-name variable-name
316
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
sreg/_ _sreg
RESTRICTIONS
• If const type is specified, or if sreg/_ _sreg is specified for a function, a warning message is output, and the
sreg declaration is ignored.
• char type uses a half the space of other types and long/float/double/long double types use twice the space
of other types.
• Between char types there are byte boundaries, but in other cases, there are word boundaries.
• When -ZA is specified, only _ _sreg is enabled and sreg is disabled.
• In the case of int/short and pointers, a maximum of 92 variables per load module is usable (when saddr area
[FE20H to FED7H] is used). Note that the number of usable variables decreases when bit and boolean type
variables, register variables, or norec and noauto functions are used (normal model).
• In the case of int/short and pointers, a maximum of 104 variables per load module is usable (when saddr
area [FE20H to FEEFH] is used). Note that the number of usable variables decreases when bit, boolean
type variables, and shared areas are used (static model).
The following shows the maximum number of sreg variables that can be used per load module.
Table 11-7. Restrictions on sreg Variable Usage
Usable Number of sreg Variables (per Load Module)
Data Type
When saddr Area [FE20H to FED7H] is Used
int/short, pointer
92 variables max.
When saddr Area [FE20H to FEEFH] is Used
Note
104 variables max.
Note
Note When bit and boolean type variables are used, the usable number decreases.
EXAMPLE
(C source)
extern sreg int hsmm0;
extern sreg int hsmm1;
extern sreg int *hsptr;
void main (
) {
hsmm0 -= hsmm1;
}
User’s Manual U14872EJ1V0UM
317
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
sreg/_ _sreg
(Assembler source)
The following example shows a definition code for an sreg variable created by the user. If an extern declaration
is not made in the C source, the C compiler outputs the following codes. In this case, the ORG quasi-directive
will not be output.
PUBLIC
_hsmm0
; Declaration
PUBLIC
_hsmm1
;
PUBLIC
_hsptr
;
DSEG
SADDRP
; Allocation to segment
ORG
0FE20H
;
_hsmm0:
DS
(2)
;
_hsmm1:
DS
(2)
;
_hsptr:
DS
(2)
;
@@DATS
(Output object of compiler)
The following codes are output in the function.
movw
ax,_hsmm0
xch
a,x
sub
a,_hsmm1
xch
a,x
subc
a,_hsmm1+1
movw
_hsmm0,ax
COMPATIBILITY
<From another C compiler to this C compiler>
• Modifications are not needed if the other compiler does not use the keyword sreg/_ _sreg.
To change to sreg variables, modifications are made according to the method shown above.
<From this C compiler to another C compiler>
• Modifications are made by #define.
For details, refer to 11.6
Modifications of C Source.
modifications allow sreg variables to be handled as ordinary variables.
318
User’s Manual U14872EJ1V0UM
These
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RD
(2) Usage with saddr automatic allocation option of external variables/external static variables
FUNCTION
• External variables/external static variables (except const type) are automatically allocated to the saddr area
regardless of whether an sreg declaration is made or not.
• Depending on the value of n, the external variables and external static variables to be allocated can be
specified as follows.
Table 11-8. Variables Allocated to saddr Area by -RD Option
Value of n
Variables Allocated to saddr Area
1
Variables of char and unsigned char types
2
Variables for when n = 1, plus variables of short, unsigned short, int, unsigned int,
enum, and pointer type
4
Variables for when n = 2, plus variables of long, unsigned long, float, double, and
long double type
When omitted
All variables (including the structures, unions, and arrays in this case only)
• Variables declared with the keyword sreg are allocated to the saddr area, regardless of the above
specification.
• The above rule also applies to variables referenced by the extern declaration, and processing is performed as
if these variables were allocated to the saddr area.
• The variables allocated to the saddr area by this option are treated in the same manner as sreg variables.
The functions and restrictions of these variables are as described in (1).
METHOD OF SPECIFICATION
Specify the -RD [n] (n: 1, 2, or 4) option.
RESTRICTIONS
• In the -RD [n] option, modules specifying a different n value cannot be linked to each other.
User’s Manual U14872EJ1V0UM
319
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RS
(3) Usage with saddr automatic allocation option of internal static variables
FUNCTION
• Automatically allocates internal static variables (except const type) to saddr area regardless of whether or
sreg declaration is made or not.
• Depending on the value of n, the internal static variables to be allocated can be specified as follows.
Table 11-9. Variables Allocated to saddr Area by -RS Option
Value of n
Variables Allocated to saddr Area
1
Variables of char and unsigned char types
2
Variables for when n = 1, plus variables of short, unsigned short, int, unsigned int,
enum, and pointer type
4
Variables if n is 2 and variables of long, unsigned long, float, double, and long
double type
When omitted
All variables (including the structures, unions, and arrays in this case only)
• Variables declared with the keyword sreg are allocated to the saddr area regardless of the above
specification.
• The variables allocated to the saddr area by this option are handled in the same manner as sreg variables.
The functions and restrictions for these variables are as described in (1).
METHOD OF SPECIFICATION
Specify the -RS [n] (n: 1, 2, or 4) option.
Remark
320
In the -RS [n] option, modules specifying a different n value can be linked to each other.
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RK
(4) Usage with saddr automatic allocation option for arguments/automatic variables
FUNCTION
• Arguments and automatic variables (except const type) are automatically allocated to the saddr area
regardless of whether an sreg declaration is made or not.
• The arguments and automatic variables to be allocated are specified using the values of n.
Table 11-10. Variables Allocated to saddr Area by -RK Option
Variables Allocated to saddr Area
Value of n
1
Variables of char and unsigned char types
2
Variables for when n = 1, plus variables of short, unsigned short, int, unsigned int,
enum, and pointer type
4
Variables for when n = 2, plus variables of long, unsigned long, float, double, and
long double type
When omitted
All variables (including the structures, unions, and arrays in this case only)
• Variables declared with sreg are allocated to the saddr area regardless of the above specifications.
• Variables allocated to the saddr area by this option are handled in the same way as sreg variables.
• Modules that have different n values specified in the -RK [n] option can be linked.
USAGE
• Specify the -RK [n] option (where n is 1, 2, or 4).
RESTRICTIONS
• Only the static model is supported. When the -SM option is not specified, a warning message is output and
the automatic allocation is ignored.
• Arguments/variables that have been declared register variables are not allocated to the saddr area.
• When the -QV option is specified simultaneously, allocation to register DE has priority.
User’s Manual U14872EJ1V0UM
321
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RK
EXAMPLE
(C source)
sub(int hsmarg)
{
int hsmauto;
hsmauto = hsmarg;
}
(Output object of compiler)
@@DATS DSEG
SADDRP
?L0003: DS
(2)
?L0004: DS
(2)
@@CODE CSEG
_sub:
movw
?L0003, ax
movw
?L0004, ax
; hsmauto
ret
322
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(4) How to use the sfr area
Usage of sfr Area
sfr
FUNCTION
• The sfr area refers to a group of special function registers such as mode registers and control registers for
the various peripherals of the 78K/0S Series microcontrollers.
• By declaring the use of sfr names, manipulations on the sfr area can be described at the C source level.
• sfr variables are external variables without initial values (undefined).
• A write check will be performed on read-only sfr variables.
• A read check will be performed on write-only sfr variables.
• Assignment of illegal data to an sfr variable will result in a compile error.
• The sfr names that can be used are those allocated to an area consisting of addresses FF00H to FFFFH.
EFFECT
• Manipulations to the sfr area can be described at the C source level.
• Instructions to the sfr area are shorter in code length than those to memory. This helps shorten object code
and also improves program execution speed.
USAGE
• Declare the use of an sfr name in the C source with the #pragma preprocessing directive, as follows (the
keyword sfr can be described in uppercase or lowercase letters.):
#pragma
sfr
• The #pragma sfr directive must be described at the beginning of the C source line.
If #pragma PC
(processor type) is specified, however, describe #pragma sfr after that.
The following statement and directives may precede the #pragma sfr directive:
• Comment statement
• Preprocessing directives that do not define or refer to a variable or function
• In the C source program, describe an sfr name that the device has as is (without change). In this case, the
sfr need not be declared.
User’s Manual U14872EJ1V0UM
323
CHAPTER 11
EXTENDED FUNCTIONS
Usage of sfr Area
sfr
RESTRICTIONS
• All sfr names must be described in uppercase letters. Lowercase letters are treated as ordinary variables.
EXAMPLE
(C source)
#ifdef _ _K0S_ _
#pragma sfr
#endif
void main()
{
P0 -= RXB00;
/* RXB00 = 10;
==> error */
}
(Output object of compiler)
Codes that relate to declarations are not output and the following codes are output in the middle of the function.
324
mov
a, P0
sub
a, RXB00
mov
P0, a
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Usage of sfr Area
sfr
COMPATIBILITY
<From another C compiler to this C compiler>
• Those portions of the C source program not dependent on the device or compiler need not be modified.
<From this C compiler to another C compiler>
• Delete the #pragma sfr statement or sort by #ifdef and add the declaration of the variable that was formerly
an sfr variable. An example is shown below.
#ifdef _ _K0S_ _
#pragma sfr
#else
/* Declaration of variables */
unsigned char P0;
#endif
void main(void) {
P0 = 0;
}
• For devices with the sfr or its alternative functions, a dedicated library must be created to access that area.
User’s Manual U14872EJ1V0UM
325
CHAPTER 11
EXTENDED FUNCTIONS
(5) noauto function
noauto Function
noauto
FUNCTION
• The noauto function sets restrictions for automatic variables not to output the codes of preprocessing/
postprocessing (generation of stack frame).
• All the arguments are allocated to registers or the saddr area (FEE4H to FEE7H) for register variables. If
there is an argument that cannot be allocated to registers, a compile error occurs.
• Automatic variables can be used only if all the automatic variables are allocated to the registers or saddr area
for register variable-use left over after argument allocation.
• The noauto function allocates arguments to the saddr area for register variable-use, but only if the -QR
option has been specified during compilation.
• The noauto function stores arguments other than arguments allocated to the registers in the saddr area for
register variable-use, and stores the arguments' descriptions in ascending sequence (refer to APPENDIX A
LIST OF LABELS FOR saddr AREA).
• The code output when calling the noauto function is the same code as the code for calling a normal function.
• When the -SM option is specified, a warning message is only output to the line in which noauto is described
first, and all the noauto functions are handled as normal functions.
EFFECT
• The object code can be shortened and execution speed can be improved.
USAGE
Declare a function with the noauto attribute in the function declaration, as follows.
noauto type-name function-name
326
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
noauto Function
noauto
RESTRICTIONS
• When the -ZA option is specified, the noauto function is disabled.
• The arguments and automatic variables of the noauto function have restrictions for their types and numbers.
The following shows the types of arguments that can be used inside a noauto function. Arguments other
than long/signed long/unsigned long, float/double/long double are allocated to register HL.
•
•
Pointer
char/signed char/unsigned char
•
int/signed int/unsigned int
•
short/signed short/unsigned short
•
long/signed long/unsigned long
•
float/double/long double
• The number of arguments and automatic variables that can be used is a maximum of 6 bytes in total size.
• These restrictions are checked at compilation.
• If arguments are declared with a register, the register declaration is ignored.
EXAMPLE
(C source)
When the -QR option is specified
noauto short nfunc(short a, short b, short c);
short l, m;
void main()
{
static short ii, jj, kk;
l = nfunc(ii, jj, kk);
}
noauto short nfunc(short a, short b, short c)
{
m = a + b + c;
return(m);
}
User’s Manual U14872EJ1V0UM
327
CHAPTER 11
EXTENDED FUNCTIONS
noauto Function
noauto
(Output object of compiler)
@@CODE CSEG
_main:
;line
5:
;line
6:
mov
xch
mov
push
mov
xch
mov
push
mov
xch
mov
call
pop
pop
movw
mov
xch
mov
;line
7:
ret
;line
8:
;line
9:
_nfunc:
push
xch
xch
xch
xch
push
movw
push
movw
movw
mov
xch
mov
movw
mov
xch
mov
movw
328
static short ii, jj, kk;
l = nfunc(ii, jj, kk);
a, !?L0005
a, x
a, !?L0005+1
ax
a, !?L0004
a, x
a, !?L0004+1
ax
a, !?L0003
a, x
a, !?L0003+1
!_nfunc
ax
ax
ax, bc
!_1+1, a
a, x
!_l, a
}
; kk
; kk
; jj
; jj
; ii
; ii
; Calls nfunc (a, b, c) function
; Assigns the return value to external variable l
noauto short nfunc (short a, short b, short c)
{
hl
a, x
a, [email protected]
a, x
a, [email protected]
ax
ax, [email protected]
ax
ax, sp
hl, ax
a,[hl+10]
a, x
a,[hl+11]
[email protected], ax
a,[hl+8]
a, x
a,[hl+9]
hl, ax
; Saves HL
;
; Sets argument a to [email protected]
;
;
; Saves [email protected]
;
; Saves [email protected]
;
;
;
;
;
; Sets argument c to [email protected]
;
;
;
; Sets argument b to HL
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
noauto Function
noauto
(Output object of compiler …continued)
;line
movw
xch
add
xch
addc
xch
add
xch
addc
mov
xch
mov
;line
xch
movw
;line
pop
movw
pop
movw
pop
ret
10: m = a + b + c;
ax, hl
a, x
a, [email protected]
a, x
a, [email protected]
a, x
a, [email protected]
a, x
a, [email protected]
!_m+1, a
a, x
!_m, a
11: return(m);
a, x
bc, ax
12: }
ax
[email protected], ax
ax
[email protected], ax
hl
;
;
;
;
;
;
;
;
; Adds b(HL) and c([email protected]) to a([email protected])
; Assigns the calculation result to external variable m
; Returns the contents of external variable m
;
; Restores [email protected]
;
; Restores [email protected]
; Restores HL
EXPLANATION
• In the above example, the noauto attribute is added at the header part of the C source.
noauto is declared and stack frame formation is not performed.
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if the keyword noauto is not used.
• To change variables to noauto variables, modify the program according to the procedure described in
USAGE above.
<From this C compiler to another C compiler>
• #define must be used. For details, see 11.6 Modifications of C Source.
User’s Manual U14872EJ1V0UM
329
CHAPTER 11
EXTENDED FUNCTIONS
(6) norec function
norec Function
norec
FUNCTION
• A function that does not call another function by itself can be changed to a norec function.
• With norec functions, code for preprocessing and postprocessing (stack frame formation) is not output.
• The arguments of the norec function are allocated to registers and saddr area (FEE8H to FEEFH) for norec
function arguments.
• If arguments cannot be allocated to registers and saddr area, a compile error occurs.
• Arguments are stored either in the register or the saddr area (FEE8H to FEEFH) and the norec function is
called.
• Automatic variables are allocated to the saddr area (FEF0H to FEF7H) and so are the register variables.
• The saddr area is not used for allocation when the -QR option is specified during compilation.
• If arguments other than long/float/double/long double types are used, the first argument is stored in register
AX, the second in register DE, and the third and successive arguments are stored in the saddr area. Note
that the arguments stored in registers AX and DE are one argument each regardless of the type of argument.
• The argument stored in register AX is copied to register DE if DE does not have the argument stored at the
beginning of the norec function. If there is an argument stored in register DE already, the argument stored in
AX is copied to [email protected] and 7.
• If automatic variables other than long/float/double/long double types are used, the arguments that are left
after allocation are stored in the declared order; DE, [email protected] and 7, and [email protected], 1...
If automatic variables long/float/double/long double types are used, the arguments that are left after
allocation are stored in the declared order; [email protected], 1...
The rest of the arguments are stored in the saddr area in the declared order (refer to APPENDIX A LIST OF
LABELS FOR saddr AREA).
EFFECT
• The object code can be shortened and program execution speed can be improved.
USAGE
Declare a function with the norec attribute in the function declaration, as follows.
norec type-name function-name
• _ _ leaf can also be described instead of norec.
330
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
RESTRICTIONS
• No other function can be called from a norec function.
• There are restrictions on the type and number of arguments and automatic variables that can be used in a
norec function.
• When -ZA is specified, norec is disabled and only _ _leaf is enabled.
• When the -SM option is specified, a warning message is only output to the line in which norec is described
first, and all the norec functions are handled as normal functions.
• The restrictions for arguments and automatic variables are checked at compilation, and an error occurs.
• If arguments and automatic variables are declared with a register, the register declaration is ignored.
• The following shows the types of arguments and automatic variables that can be used in norec functions.
norec functions are allocated to the saddr area consecutively if between char/signed char/unsigned char,
however if connected to other types, allocation is performed in two-byte alignment.
•
•
Pointer
char/signed char/unsigned char
•
int/signed int/unsigned int
•
short/signed short/unsigned short
•
long/signed long/unsigned long
•
float/double/long double
(When the -QR option is not specified)
• The number of arguments that can be used in a norec function is 2 variables, if other than
long/float/double/long double types. Arguments cannot be used for long/float/double/long double types.
• Automatic variables can use the area that is the combined total of the number of bytes remaining unused by
arguments. If types other than long/float/double/long double are used, automatic variables can use up to 4
bytes. Arguments can not be used for long/float/double/long double types.
(When the -QR option is specified)
• The number of arguments is 6 variables, if types other than long/float/double/long double are used, and 2
variables if long/float/double/long double types are used.
• Automatic variables can use the area that is the combined total of the number of bytes remaining unused by
arguments and the number of saddr area bytes. If types other than long/float/double/long double are used,
automatic variables can use up to 20 bytes and if long/float/double/long double types are used, automatic
variables can use up to 16 bytes.
• These restrictions are checked at compilation and an error will occur if not satisfied.
User’s Manual U14872EJ1V0UM
331
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
EXAMPLE
(C source)
norec int rout (int a, int b, int c);
int i, j;
void main (
) {
int k, l, m;
i = l + rout (k, l, m) + ++k ;
}
norec int rout (int a, int b, int c)
{
int x, y;
return
(x + (a<<2) );
}
332
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
(Output object of compiler)
When the -QR option is specified
EXTRN
[email protected]
; References saddr area to be used
EXTRN
[email protected]
;
EXTRN
[email protected]
;
← m
; Stores argument in saddr area
← 1
; Stores argument to DE
ax
← k
; Stores argument in AX
call
!_rout
; Calls norec function
.
.
.
[email protected]
.
.
.
de
.
.
.
_rout:
movw
[email protected], ax
; Receives argument from saddr area
mov
c, #02H
xch
a, x
add
a, a
xch
a, x
rolc
a, 1
dbnz
c, $$-5
xch
a, x
add
a, [email protected]
xch
a, x
;
addc
a, [email protected]+1
; Uses automatic variables of saddr area
movw
bc, ax
;
; Uses automatic variables of saddr area
ret
User’s Manual U14872EJ1V0UM
333
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
EXPLANATION
In the above example, the norec attribute is added in the definition of the rout function as well to indicate that
the function is norec.
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if the keyword norec is not used.
• To change variables to norec variables, modify the program according to the procedure described in USAGE
above.
<From this C compiler to another C compiler>
• #define must be used. For details, see 11.6 Modifications of C Source.
334
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(7) bit type variables
bit Type Variables
boolean Type Variables
bit
boolean
_ _boolean
FUNCTION
• A bit or boolean type variable is handled as 1-bit data and allocated to the saddr area.
• These variables can be handled the same as external variables that have no initial value (or have an unknown
value).
• The C compiler outputs the following bit manipulation instructions for these variables.
SET1, CLR1, NOT1, BT, BF instruction
EFFECT
• Programming at the assembler source level can be performed in C, and the saddr and sfr areas can be
accessed in bit units.
USAGE
• Declare a bit or boolean type inside a module in which the bit or boolean type variable is to be used, as
follows:
• _ _boolean can also be described instead of bit.
bit variable-name
boolean variable-name
_ _boolean variable-name
• Declare a bit or boolean type inside a module in which the bit or boolean type variable is to be used, as
follows.
extern
bit variable-name
extern
boolean variable-name
extern
_ _boolean variable-name
• char, int, short, and long type sreg variables (except the elements of arrays and members of structures) and
8-bit sfr variables can be automatically used as bit type variables.
variable-name. n (where n = 0 to 31)
User’s Manual U14872EJ1V0UM
335
CHAPTER 11
EXTENDED FUNCTIONS
bit Type Variables
boolean Type Variables
bit
boolean
_ _boolean
RESTRICTIONS
• An operation on two bit or boolean type variables is performed by using the CY (carry) flag.
For this reason, the contents of the carry flag between statements are not guaranteed.
• Arrays cannot be defined or referenced.
• A bit or boolean type variable cannot be used as a member of a structure or union.
• This type of variable cannot be used as the argument type of a function.
• A bit type variable cannot be used as the type of an automatic variable (other than static model).
• With bit type variables only, up to 1472 variables can be used per load module (when saddr area [FE20H to
FED7H] is used) (normal model).
• With bit type variables only, up to 1664 variables can be used per load module (when saddr area [FE20H to
FEEFH] is used) (static model).
• The variable cannot be declared with an initial value.
• If the variable is described along with a const declaration, the const declaration is ignored.
• Only operations using 0 and 1 can be performed by the operators and constants shown in Table 11-11.
• *, & (pointer reference, address reference), and sizeof operations cannot be performed.
• When the -ZA option is specified, only _ _boolean is enabled.
Table 11-11. Operators Using Only Constants 0 or 1 (with Bit Type Variable)
Classification
Remark
Operator
Assignment
=
Bitwise AND
&, &=
Bitwise XOR
^, ^=
Logical AND
Equal
Classification
Bitwise OR
|, |=
&&
Logical OR
||
==
Not Equal
!=
If sreg variables are used or if -RD, -RS, and -RK (saddr automatic allocation option) options are
specified, the number of usable bit type variables decreases.
336
Operator
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
bit Type Variables
boolean Type Variables
bit
boolean
_ _boolean
EXAMPLE
(C source)
#define ON 1
#define OFF 0
extern bit data1;
extern bit data2;
void main()
{
data1 = ON;
data2 = OFF;
while(data1)
{
data1 = data2;
testb();
}
if(data1 && data2){
chgb();
}
}
(Assembler source)
This example is for cases when the user has generated a definition code for a bit type variable. If an extern
declaration has not been attached, the compiler outputs the following code. The ORG quasi-directive is not
output in this case.
PUBLIC
_data1
PUBLIC
_data2
@@BITS
; Declaration
; Allocation to segment
BSEG
ORG
_data1
DBIT
_data2
DBIT
0FE20H
User’s Manual U14872EJ1V0UM
337
CHAPTER 11
EXTENDED FUNCTIONS
bit Type Variables
boolean Type Variables
bit
boolean
_ _boolean
(Output object of compiler)
The following codes are output in a function.
set1
_data1
; Initialized
clr1
_data2
; Initialized
bf
_data1, $?L0001
; Judgment
bf
_data1, $?L0005
; Logical AND expression
bf
_data2, $?L0005
; Logical AND expression
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if the keyword bit, boolean, or _ _boolean is not used.
• To change variables to bit or boolean type variables, modify the program according to the procedure
described in USAGE above.
<From this C compiler to another C compiler>
• #define must be used. For details, see 11.6 Modifications of C Source (as a result of this, the bit or
boolean type variables are handled as ordinary variables.).
338
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(8) ASM statements
ASM Statements
#asm, #endasm
_ _asm
FUNCTION
(a) #asm - #endasm
• The assembler source program described by the user can be embedded in an assembler source file to
be output by this C compiler by using the preprocessing directives #asm and #endasm.
• #asm and #endasm lines will not be output.
(b) _ _asm
• An assembly instruction is output by describing an assembly code to a character string literal and is
inserted in an assembler source.
EFFECT
• The global variables of the C source can be manipulated in the assembler source
• Functions that cannot be described in the C source can be implemented
• The assembler source output by the C compiler can be hand-optimized and embedded in the C source (to
obtain efficient objects)
USAGE
(a) #asm - #endasm
• Indicate the start of the assembler source with the #asm directive and the end of the assembler source
with the #endasm directive. Describe the assembler source between #asm and #endasm.
#asm
.
.
/*assembler source*/
.
#endasm
(b) _ _asm
• Use of _ _asm is declared by the #pragma asm specification made at the beginning of the module in
which the ASM statement is to be described (uppercase letters and lowercase letters are distinguished
for the keywords following #pragma).
• The following items can be described before #pragma asm.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• The ASM statement is described in the following format in the C source.
_ _asm (string literal);
• The description method of a character string literal conforms to ANSI, and a line can be continued by using an
escape character string (\n: line feed, \t: tab) or ¥, or character strings can be linked.
User’s Manual U14872EJ1V0UM
339
CHAPTER 11
EXTENDED FUNCTIONS
ASM Statements
#asm, #endasm
_ _asm
RESTRICTIONS
• Nesting of #asm directives is not allowed.
• If ASM statements are used, no object module file will be created. Instead, an assembler source file will be
created.
• Only lowercase letters can be described for _ _asm. If _ _asm is described with uppercase and lowercase
characters mixed, it is regarded as a user function.
• When the -ZA option is specified, only _ _asm is enabled.
• #asm - #endasm and _ _asm can only be described inside a function of the C source. Therefore, the
assembler source is output to CSEG with the segment name @@CODE.
EXAMPLE
(a) #asm - #endasm
(C source)
void main (
) {
#asm
callt [init]
#endasm
}
(Output object of compiler)
The assembler source written by the user is output to the assembler source file.
@@CODE
CSEG
_main:
callt
[init]
ret
END
EXPLANATION
• In the above example, statements between #asm and #endasm will be output as an assembler source
program to the assembler source file.
340
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
ASM Statements
#asm, #endasm
_ _asm
(b) _ _asm
(C source)
#pragma asm
int
a,
void
b;
main (
) {
_ _ asm(“\tmovw ax,
_ _ asm(“\tmovw
_b,
_a\t;ax
<-
ax\t;b <-
a”);
ax”);
}
(Assembler source)
@@CODE CSEG
_main:
movw
ax,
_a
;ax
<-
a
movw
_b,
ax
;b
<-
ax
ret
END
COMPATIBILITY
• With a C compiler that supports #asm, modify the program according to the format specified by the C
compiler.
• If the target device is different, modify the assembler source part of the program.
User’s Manual U14872EJ1V0UM
341
CHAPTER 11
EXTENDED FUNCTIONS
(9) Interrupt functions
Interrupt Functions
#pragma vect
#pragma interrupt
FUNCTION
• The address of a described function name is registered to an interrupt vector table corresponding to a
specified interrupt request name.
• An interrupt function outputs a code to save or restore the following data (except that used in the ASM
statement) to or from the stack at the beginning and end of the function:
(1)
Registers
(2)
saddr area for register variables
(3)
saddr area for arguments/auto variables of norec function (regardless of whether the arguments or
(4)
saddr area for runtime library (normal model only)
variables are used)
Note, however, that depending on the specification or status of the interrupt function, saving/restoring is
performed differently, as follows.
• If “no change” is specified, codes that save/restore register contents, and that save/restore the contents of the
saddr area are not output regardless of whether the codes are used or not.
• If “no change” is not specified and if a function is called in the interrupt function, however, the entire register
area is saved or restored, regardless of whether use of registers is specified or not.
(Normal model)
• If the -QR option is not specified at compilation, the saddr area for register variables and the saddr area for
the arguments/auto variables of the norec function is not used; therefore, the save/restore code is not output.
If the size of the save code is smaller than that of the restore code, the restore code is output.
• Table 11-12 summarizes the above and shows the save/restore area.
342
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect
#pragma interrupt
Table 11-12. Save/Restore Area When Interrupt Function Is Used
Function Called
Save/Restore Area
Function Not Called
NO BANK
Without -QR
With -QR
Without -QR
With -QR
Register used
×
×
×
√
√
All registers
×
√
√
×
×
saddr area for runtime library used
×
×
×
√
√
saddr area for all runtime libraries
×
√
√
×
×
saddr area for register variable used
×
×
√
×
√
All saddr area for arguments/auto
variables of norec function
×
×
√
×
×
√: Saved
× : Not saved
(Static model)
• Since the saddr area for register variables, the saddr area for automatic variables or norec function
arguments, and the saddr area for the runtime library is not used when the -SM option is specified during
compilation, only the save and restore code for registers is output; not the code for saddr area. However,
when leafwork 1 to 16 has been specified, the code for saving and restoring the byte number to the stack is
output from the higher-level address of shared area at the beginning and end of the interrupt function (Refer
to 11.5 (23) Static model when the -ZM option is not specified, and 11.5 (32) Static model expansion
specification when the -ZM option is specified).
Caution
If there is an ASM statement in an interrupt function, and if the area reserved for registers of
the compiler is used in that ASM statement, the area must be saved by the user.
User’s Manual U14872EJ1V0UM
343
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect
#pragma interrupt
EFFECT
• Interrupt functions can be described at the C source level.
• It is not necessary to be aware of the addresses of the vector table to recognize an interrupt request name.
USAGE
• Specify an interrupt request name, a function name, stack switching, registers, and whether the saddr area is
saved/restored, with the #pragma directive. Describe the #pragma directive at the beginning of the C source
(for the interrupt request names, refer to the user’s manual of the target device used).
• When describing #pragma PC (processor type), describe this #pragma directive after that. The following
items can be described before this #pragma directive.
• Comment statements
• Preprocessing directives that neither define nor reference variables or functions
#pragma∆vect (or interrupt)∆interrupt request name∆function name∆
[stack change specification] ∆
stack use specification
No change specification
Shared area save/restore specification
Save/restore target
344
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect
#pragma interrupt
Interrupt request name:
Described in uppercase letters. Refer to the user’s manual of the
target device used (example: NMI, INTP0, etc.).
Function name:
Name of the function that describes interrupt processing
Stack change specification:
SP = array name [+ offset location] (example: SP = buff + 10)
Define the array by unsigned char (example: unsigned char buff
[10];).
Stack use specification:
STACK (default)
No change specification:
NOBANK
Shared area save/restore specification:
leafwork 1 to 16 (when -SM option specified)
Save/restore target:
SAVE_R Save/restore target limited to registers
SAVE_RN Save/restore target limited to registers and [email protected]
(when -SM, -ZM option specified)
∆:
Space
RESTRICTIONS
• Register bank specification is not supported.
• An interrupt request name must be described in uppercase letters.
• A duplication check on interrupt request names will be made within only one module.
• If the same or another interrupt occurs due to the contents of the priority specification flag register and
interrupt mask flag register while a vectored interrupt is processed, the contents of the registers may be
changed if no change is specified, resulting in an error. The compiler, however, cannot check this error.
• callt/noauto/norec/_ _callt/_ _leaf/_ _pascal cannot be specified as the interrupt functions.
• An interrupt function is specified with void type (example: void func (void);) because it cannot have an
argument or a return value.
• Even if an ASM statement exists in the interrupt function, codes saving all the registers and variable areas are
not output. If an area reserved for the compiler is used in the ASM statement in the interrupt function,
therefore, or if a function is called in the ASM statement, the user must save the registers and variable areas.
• If a function specifying no change, register bank, or stack change as the saving destination in #pragma
vect/#pragma interrupt specification is not defined in the same module, a warning message is output and
the stack change is ignored. In this case, the default stack is used.
User’s Manual U14872EJ1V0UM
345
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect
#pragma interrupt
• When stack change is specified, the stack pointer is changed to the location where the offset is added to the
array name symbol. The area of the array name is not secured by the #pragma directive. It needs to be
defined separately as a global unsigned char type array.
• The code that changes the stack pointer is generated at the start of a function, and the code that sets the
stack pointer back is generated at the end of a function.
• When keywords sreg/_ _sreg are added to the array for stack change, it is assumed that two or more
variables with the different attributes and the same name are defined, and a compile error occurs. It is
possible to allocate an array in saddr area by the -RD option, but code and speed efficiency will not be
improved because the array is used as a stack. It is recommended to use the saddr area for purposes other
than a stack.
• The stack change cannot be specified simultaneously with the no change. If specified so, an error occurs.
• The stack change must be described before the stack use specification. If the stack change is described after
the stack use specification, an error occurs.
• If leafwork 1 to 16 is specified when the -SM option is not specified, a warning is output and the save/restore
specification of the shared area is ignored.
EXAMPLE
(C source)
When there is a shared area (static model only)
#pragma interrupt INTP0 inter leafwork4
void func();
void inter()
{
func();
}
346
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect
#pragma interrupt
(Compiler output object)
EXTRN
EXTRN
@@CODE CSEG
_inter:
push
push
push
movw
push
movw
push
call
pop
movw
pop
movw
pop
pop
pop
reti
@@VECT06
[email protected]:
DW
[email protected]
[email protected]
ax
bc
hl
ax, [email protected]
ax
ax, [email protected]
ax
!_func
ax
[email protected], ax
ax
[email protected], ax
hl
bc
ax
CSEG
AT
; Saves the register
; Saves the register
; Saves the register
; Saves the shared area
; Saves the shared area
; Saves the shared area
; Saves the shared area
; Restores the shared area
; Restores the shared area
; Restores the shared area
; Restores the shared area
; Restores registers
; Restores registers
; Restores registers
0006H
_inter
User’s Manual U14872EJ1V0UM
347
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect
#pragma interrupt
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if interrupt functions are not used at all.
• To change an ordinary function to an interrupt function, modify the program according to the procedure
described in USAGE above.
<From this C compiler to another C compiler>
• An interrupt function can be used as an ordinary function by deleting its specification with the #pragma vect
or #pragma interrupt directive.
• When an ordinary function is to be used as an interrupt function, change the program according to the
specifications of each compiler.
348
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(10) Interrupt function qualifier (_ _interrupt)
Interrupt Function Qualifier
_ _interrupt
FUNCTION
• A function declared with the _ _interrupt qualifier is regarded as a hardware interrupt function, and execution
is returned by the return RETI instruction for the non-maskable/maskable interrupt function.
• A function declared with this qualifier is regarded as a (non-maskable/maskable) interrupt function, and saves
or restores the registers and variable areas (1) and (4) below, which are used as the work area of the
compiler, to or from the stack.
If a function call is described in this function, however, all the variable areas are saved to the stack.
(1) Registers
(2) saddr area for register variables
(3) saddr area for arguments/auto variables of norec function (regardless of whether used or not)
(4) saddr area for runtime library
Remark
If the -QR option is not specified (default) at compilation, save/restore codes are not output because
areas (2) and (3) are not used. If the -SM option is specified at compilation, save/restore codes are
not output because areas (2), (3) and (4) are not used.
EFFECT
• By declaring a function with this qualifier, the setting of a vector table and interrupt function definition can be
described in separate files.
USAGE
• Describe _ _interrupt as the qualifier of an interrupt function.
(For non-maskable/maskable interrupt function)
_ _interrupt void func() {processing}
RESTRICTIONS
• _ _interrupt_brk is not supported because there is no software interrupt. A warning message is output
where _ _interrupt_brk first appeared, the keyword is ignored, and _ _interrupt_brk is handled as a normal
function.
• The interrupt function cannot specify callt/noauto/norec/_ _callt/_ _leaf/_ _pascal.
User’s Manual U14872EJ1V0UM
349
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Function Qualifier
_ _interrupt
CAUTIONS
• The vector address is not set by merely declaring this qualifier. The vector address must be separately set by
using the #pragma vect/interrupt directive or assembler description.
• The saddr area and registers are saved to the stack.
• Even if the vector address is set or the saving destination is changed by #pragma vect (or interrupt) ..., the
change in the saving destination is ignored if there is no function definition in the same file, and the default
stack is assumed.
• To define an interrupt function in the same file as the #pragma vect (or interrupt) ... specification, the
function name specified by #pragma vect (or interrupt) ... is judged as the interrupt function, even if this
qualifier is not described (for details of #pragma vect/interrupt, refer to USAGE of 11.5 (9)
Interrupt
functions).
EXAMPLE
Declare or define interrupt functions in the following format. The code to set the vector address is generated by
#pragma interrupt.
#pragma interrupt INTP0 inter
_ _interrupt void inter(
);
_ _interrupt void inter(
)
/*prototype declaration*/
{processing};
/*function body*/
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified unless interrupt functions are supported.
• Modify the interrupt functions, if necessary, according to the procedure described in USAGE above.
<From this C compiler to another C compiler>
• #define must be used to allow the interrupt qualifiers to be handled as ordinary functions.
• To use the interrupt qualifiers as interrupt functions, modify the program according to the specifications of
each compiler.
350
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(11) Interrupt functions
Interrupt Functions
#pragma DI
#pragma EI
FUNCTIONS
• The DI and EI codes are output to an object and an object file is created.
• If there is no #pragma directive, DI( ) and EI( ) are regarded as ordinary functions.
• If “DI(
);” is described at the beginning of a function (except the declaration of an automatic variable,
comment, and preprocessing directive), the DI code is output before the preprocessing of the function
(immediately after the label of the function name).
• To output the DI code after the preprocessing of the function, open a new block before describing “DI( );”
(delimit this block with ‘{‘).
• If “EI( );” is described at the end of a function (except comments and preprocessing directives), the EI code is
output after the postprocessing of the function (immediately before the code RET).
• To output the EI code before the postprocessing of a function, close a new block after describing “EI( );”
(delimit this block with ‘}’).
EFFECT
• A function disabling interrupts can be created.
USAGE
• Describe the #pragma DI and #pragma EI directives at the beginning of the C source.
However, the
following items may precede the #pragma DI and #pragma EI directives.
•
Comment statements
•
Other #pragma directives
•
Preprocessing directives that neither define nor reference variables or functions
• Describe DI( ); or EI( ); in the source in the same manner as a function call.
• DI and EI can be described in either uppercase or lowercase letters after #pragma.
User’s Manual U14872EJ1V0UM
351
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma DI
#pragma EI
RESTRICTIONS
• When using these interrupt functions, DI and EI cannot be used as function names.
• DI and EI must be described in uppercase letters. If described in lowercase letters, they will be handled as
ordinary functions.
EXAMPLE
#ifdef _ _K0S_ _
#pragma DI
#pragma EI
#endif
(C source 1)
#pragma
DI
#pragma
EI
void
main (
)
{
DI (
);
function body
EI ( );
}
(Output object of compiler)
_main:
di
preprocessing
function body
postprocessing
ei
ret
352
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma DI
#pragma EI
<To output DI and EI after and before preprocessing/postprocessing>
(C source 2)
#pragma
DI
#pragma
EI
void main (
)
{
{
DI (
);
function body
EI ( );
}
}
(Output object of compiler)
_main:
preprocessing
di
function body
ei
post-processing
ret
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if interrupt functions are not used at all.
• To change an ordinary function to an interrupt function, modify the program according to the procedure
described in USAGE above.
<From this C compiler to another C compiler>
• DI and EI can be used as ordinary function names (example: #ifdef_ _K0S_ _ ... #endif) by deleting the
#pragma DI and #pragma EI directives or delimiting them with #ifdef.
• To use an ordinary function as an interrupt function, modify the program according to the specifications of
each compiler.
User’s Manual U14872EJ1V0UM
353
CHAPTER 11
EXTENDED FUNCTIONS
(12) CPU control instruction
CPU Control Instruction
#pragma HALT/STOP/NOP
FUNCTION
• The following codes are output to the object to create an object file.
(1)
Instruction for HALT operation (HALT)
(2)
Instruction for STOP operation (STOP)
(3)
NOP instruction
EFFECT
• The standby function of a microcontroller can be used with a C program.
• The clock can be advanced without the CPU operating.
USAGE
• Describe the #pragma HALT, #pragma STOP, and #pragma NOP instructions at the beginning of the C
source.
• The following items can be described before the #pragma directive.
• Comment statements
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• The keywords following #pragma can be described in either uppercase or lowercase letters.
• Describe as follows in uppercase letters in the C source in the same format as a function call.
(1)
HALT (
(2)
STOP (
(3)
NOP (
);
);
);
RESTRICTIONS
• When this feature is used, HALT( ), STOP( ), and NOP( ) cannot be used as function names.
• Describe HALT, STOP, and NOP in uppercase letters. If they are described in lowercase letters, they are
handled as ordinary functions.
354
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
CPU Control Instruction
#pragma HALT/STOP/NOP
EXAMPLE
(C source)
#pragma HALT
#pragma STOP
#pragma NOP
main (
)
{
HALT (
);
STOP (
);
NOP (
);
}
(Output object of compiler)
@@CODE
CSEG
_main:
halt
stop
nop
COMPATIBILITY
<From another C compiler to this C compiler>
• The C source program need not be modified if the CPU control instructions are not used.
• Modify the program according to the procedure described in USAGE above when the CPU control instructions
are used.
<From this C compiler to another C compiler>
• HALT, STOP, and NOP can be used as function names by deleting the “#pragma HALT”, “#pragma STOP”,
and “#pragma NOP” statements or delimiting them with #ifdef.
• To use these instructions as the CPU control instructions, modify the program according to the specifications
of each compiler (such as #asm, #endasm, and asm();).
User’s Manual U14872EJ1V0UM
355
CHAPTER 11
EXTENDED FUNCTIONS
(13) Absolute address access function
Absolute Address Access Function
#pragma access
FUNCTION
• A code to access the ordinary RAM space is output to the object through direct inline expansion, not by
function call, and an object file can be created.
• If the #pragma directive is not described, a function accessing an absolute address is regarded as an
ordinary function.
EFFECT
• A specific address in the ordinary memory space can be easily accessed through C description.
USAGE
• Describe the #pragma access directive at the beginning of the C source.
• Describe the directive in the source in the same format as a function call.
• The following items can be described before #pragma access.
• Comment statements
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• The keywords following #pragma can be described in either uppercase or lowercase letters.
The following four function names are available for absolute address accessing.
peekb, peekw, pokeb, pokew
356
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Access Function
#pragma access
[List of functions for absolute address accessing]
(a) unsigned char peekb (addr);
unsigned int addr;
Returns 1-byte contents of address addr.
(b) unsigned int peekw (addr);
unsigned int addr;
Returns 2-byte contents of address addr.
(c) void pokeb (addr, data);
unsigned int addr;
unsigned char data;
Writes 1-byte contents of data to the position indicated by address addr.
(d) void pokew (addr, data);
unsigned int addr;
unsigned int data;
Writes 2-byte contents of data to the position indicated by address addr.
RESTRICTIONS
• A function name for absolute address accessing must not be used.
• Describe functions for absolute address accessing in lowercase letters. Functions described in uppercase
letters are handled as ordinary functions.
User’s Manual U14872EJ1V0UM
357
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Access Function
EXAMPLE
(C source)
#pragma
char
int
access
a;
b;
void main (
)
{
a = peekb (0x1234);
a = peekb (0xfe23);
b = peekw (0x1256);
b = peekw (0xfe68);
pokeb (0x1234, 5);
pokeb (0xfe23, 5);
pokew (0x1256, 7);
pokew (0xfe68, 7);
}
358
User’s Manual U14872EJ1V0UM
#pragma access
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Access Function
#pragma access
(Output assembler source)
.
.
.
.
.
.
mov
a, !01234H
mov
!_a, a
mov
a, 0FE23H
mov
!_a, a
mov
a, !01256H
xch
a, x
mov
a, !01257H
movw
de, #_b
callt
[@@deist]
movw
ax, 0FE68H
callt
[@@deist]
mov
a, #05H
mov
!01234H, a
mov
0FE23H, #05H
movw
ax, #07H
mov
!01257H, a
xch
a, x
mov
!01256H, a
movw
ax, #07H
movw
0FE68H, ax
COMPATIBILITY
<From another C compiler to this C compiler>
• The source program need not be modified if a function for absolute address accessing is not used.
• Modify the program according to the procedure described in USAGE above if a function for absolute address
accessing is used.
<From this compiler to another C compiler>
• The function name of absolute address accessing can be used as a function name by deleting the “#pragma
access” statement or delimiting it with #ifdef.
• To use a function for absolute address accessing, modify the program according to the specifications of each
compiler (#asm, #endasm, asm, etc.).
User’s Manual U14872EJ1V0UM
359
CHAPTER 11
EXTENDED FUNCTIONS
(14) Bit field declaration
Bit Field Declaration
Bit field declaration
(1) Extension of type specifier
FUNCTION
• The bit field of unsigned char type is not allocated straddling over a byte boundary.
• The bit field of unsigned int type is not allocated straddling over a word boundary, but can be allocated
straddling over a byte boundary.
• The bit fields of the same type are allocated in the same byte units (or word units). If the types are different,
the bit fields are allocated in different byte units (or word units).
EFFECT
• The memory can be saved, the object code can be shortened, and the execution speed can be improved.
USAGE
• As a bit field type specifier, unsigned char type can be specified in addition to unsigned int type. Declare as
follows.
struct
tag-name {
unsigned char Field name: bit width;
unsigned char Field name: bit width;
.
.
.
unsigned int
Field name: bit width;
};
EXAMPLE
struct tagname {
unsigned char A: 1;
unsigned char B: 1;
.
.
.
unsigned int
C: 2;
unsigned int
D: 1;
.
.
.
360
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
COMPATIBILITY
<From another C compiler to this C compiler>
• The source program need not be modified.
• Change the type specifier to use unsigned char as the type specifier.
<From this C compiler to another C compiler>
• The source program need not be modified if unsigned char is not used as a type specifier.
• Change unsigned char, if it is used as a type specifier, into unsigned int.
(2) Allocation direction of bit field
FUNCTION
• The direction in which a bit field is to be allocated is changed and the bit field is allocated from the MSB side
when the -RB option is specified.
• If the -RB option is not specified, the bit field is allocated from the LSB side.
USAGE
• Specify the -RB option at compile time to allocate the bit field from the MSB side.
• Do not specify the option to allocate the bit field from the LSB side.
EXAMPLE 1
(Bit field declaration)
struct t {
unsigned char A:1;
unsigned char B:1;
unsigned char C:1;
unsigned char D:1;
unsigned char E:1;
unsigned char F:1;
unsigned char G:1;
unsigned char H:1;
};
User’s Manual U14872EJ1V0UM
361
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
EXPLANATION
Because a through h are 8 bits or less, they are allocated in 1-byte units.
Figure 11-1. Bit Allocation by Bit Field Declaration (Example 1)
Bit allocation from MSB
Bit allocation from LSB
with -RB option specified
without -RB option specified
MSB
A
B
C
D
E
F
G
LSB
MSB
H
H
LSB
G
EXAMPLE 2
(Bit field declaration)
struct t {
char
a;
unsigned char
b:2;
unsigned char
c:3;
unsigned char
d:4;
int
e;
unsigned char
f:5;
unsigned char
g:6;
unsigned char
h:2;
unsigned int
i:2;
};
362
User’s Manual U14872EJ1V0UM
F
E
D
C
B
A
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
EXPLANATION
Figure 11-2. Bit Allocation by Bit Field Declaration (Example 2)
Bit field allocated from the MSB side
Bit field allocated from the LSB side
when the -RB option is specified
when the -RB option is not specified
MSB
LSB
b
c
Vacant
LSB
Vacant
a
1
MSB
c
b
a
1
0
0
Member a of char type is allocated to the first byte unit. Members b and c are allocated to subsequent byte
units, starting from the second byte unit. If a byte unit does not have enough space to hold the type char
member, that member will be allocated to the following byte unit. In this case, if there is only space for 3 bits in
the second byte unit, and member d has four bits, it will be allocated to the third byte unit.
Vacant
d
Vacant
Vacant
Vacant
d
3
2
3
2
e
e
e
e
5
4
5
4
f
g
g
7
Vacant
Vacant
Vacant
7
6
h
9
g
Vacant
Vacant
9
8
g
f
6
Vacant
h
8
Since member g is a bit field of type unsigned int, it can be allocated across byte boundaries. Since h is a bit
field of type unsigned char, it is not allocated in the same byte unit as the g bit field of type unsigned int, but is
allocated in the next byte unit.
i
Vacant
11
Vacant
Vacant
10
11
Vacant
i
10
Since i is a bit field of type unsigned int, it is allocated in the next word unit.
User’s Manual U14872EJ1V0UM
363
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
When the -RC option is specified (to pack the structure members), the above bit field becomes as follows.
b
c
Vacant
1
e
g
h
Vacant
e
5
4
Vacant
9
Remark
Vacant
2
7
i
d
b
a
f
0
e
Vacant
3
g
e
5
g
Vacant
6
7
Vacant
Vacant
8
9
d
2
f
4
h
Vacant
g
6
Vacant
i
8
The numbers below the allocation diagrams indicate the byte offset values from the beginning of the
structure.
364
c
1
0
3
Vacant
Vacant
a
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
EXAMPLE 3
(Bit field declaration)
struct t {
char
a;
unsigned int
b:6;
unsigned int
c:7;
unsigned int
d:4;
unsigned char
e:3;
unsigned char
f:10;
unsigned char
g:2;
unsigned char
h:5;
unsigned int
i:6;
};
Figure 11-3. Bit Allocation by Bit Field Declaration (Example 3)
Bit field allocated from the MSB side
Bit field allocated from the LSB side
when the -RB option is specified
when the -RB option is not specified
MSB
LSB
MSB
LSB
Vacant
a
Vacant
a
1
0
1
0
b
c
c
3
Vacant
Vacant
2
c
c
b
3
2
Since b and c are bit fields of type unsigned int, they are allocated from the next word unit.
Since d is also a bit field of type unsigned int, it is allocated from the next word unit.
d
Vacant
5
Vacant
7
Vacant
Vacant
4
5
e
Vacant
6
Vacant
7
Vacant
d
4
Vacant
e
6
Since e is a bit field of type unsigned char, it is allocated to the next byte unit.
User’s Manual U14872EJ1V0UM
365
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
f
Bit field declaration
f
g
9
Vacant
Vacant
g
i
i
8
Vacant
Vacant
11
f
9
8
h
f
i
i
11
10
h
10
f and g, and h and i are each allocated to separate word units.
When the -RC option is specified (to pack the structure members), the above bit field becomes as follows.
MSB
LSB
c
Vacant
d
f
g
7
i
Vacant
4
g
f
f
7
Vacant
Vacant
8
6
i
9
c
2
e
Vacant
i
h
8
The numbers below the allocation diagrams indicate the byte offset values from the beginning of the
structure.
366
Vacant
5
Vacant
i
d
Vacant
6
9
Remark
Vacant
4
f
0
3
Vacant
5
h
c
2
Vacant
a
1
b
3
e
b
0
Vacant
LSB
c
a
1
MSB
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
COMPATIBILITY
<From another C compiler to this C compiler>
• The source program need not be modified.
<From this C compiler to another C compiler>
• The source program must be modified if the -RB option is used and coding is performed taking the bit field
allocation sequence into consideration.
User’s Manual U14872EJ1V0UM
367
CHAPTER 11
EXTENDED FUNCTIONS
(15) Changing compiler output section name
#pragma section…
#pragma section…
FUNCTION
• A compiler output section name is changed and a start address is specified. If the start address is omitted,
the default allocation is assumed. For the compiler output section name and default location, refer to
APPENDIX B LIST OF SEGMENT NAMES. In addition, the location of sections can be specified by omitting
the start address and using the link directive file at the time of link. For the link directives, refer to the
RA78K0S Assembler Package User’s Manual Operations (U14876E).
• To change the section name @@CALT with an AT start address specified, the callt function must be
described before or after the other functions in the source file.
• If data is described after the #pragma directive is described, that data is located in the data change section.
Another change directive is possible, so if data is described after the rechange directive, that data is located
in the rechange section. If data defined before a change is redefined after the change, it is located in the
rechanged section. Furthermore, this is valid in the same way for static variables (within the function).
EFFECT
• Changing the compiler output section repeatedly in one file enables location of each section independently,
so that data can be located in the desired data units.
USAGE
• Specify the name of the section to be changed, a new section name, and the start address of the section, by
using the #pragma directive as indicated below.
Describe this #pragma directive at the beginning of the C source.
Describe this #pragma directive after #pragma PC (processor type).
The following items can be described before this #pragma directive.
• Comment statements
• Preprocessing directives that neither define nor reference variables or functions
However, all sections in BSEG and DSEG, and the @@CNST section in CSEG can be described anywhere in
the C source, and rechange directives can be performed repeatedly. To return to the original section name,
describe the compiler output section name in the changed section.
Declare as follows at the beginning of the file.
#pragma
section compiler output section name new section name [AT start address]
• Of the keywords to be described after #pragma, be sure to describe the compiler output section name in
uppercase letters. section, AT can be described in either uppercase or lowercase letters, or in a combination
of both.
368
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
• The format in which the new section name is to be described must conform to the assembler specifications
(up to eight letters can be used for a segment name).
• Only the hexadecimal numbers of the C language and the hexadecimal numbers of the assembler can be
described as the start address.
[Hexadecimal numbers of C language]
0xn / 0xn...n
0Xn / 0xn...n
(n = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)
[Hexadecimal numbers of assembler]
nH/n...nH
nh/n...nh
(n = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)
• The hexadecimal number must start with a numeral.
Example:
To express a numeric value with a value of 255 as a hexadecimal number, specify zero before F.
It is therefore 0FFH.
• For sections other than the @@CNST section in CSEG, that is, sections in which functions are located, this
#pragma directive cannot be described other than at the beginning of the C source (after the C text is
described); otherwise it causes an error.
• If this #pragma directive is executed after the C text is described, an assembler source file is created without
an object module file being created.
• If this #pragma directive is after the C text is described, a file that contains this #pragma directive and that
does not have the C text (including external reference declarations for variables and functions) cannot be
included. This results in an error (refer to the error description in Example 1).
• An #include statement cannot be described in a file that executes this #pragma directive following the C text
description. If described, it causes an error. (refer to the following error description in Example 2).
• If the #include statement follows the C text, this #pragma directive cannot be described after this description.
If described, it causes an error (refer to the following error description in Example 3).
User’s Manual U14872EJ1V0UM
369
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
EXAMPLE 1
Section name @@CODE is changed to CC1 and address 2400H is specified as the start address.
(C source)
#pragma
section @@CODE
void
main()
CC1 AT 2400H
{
Function body
}
(Output object)
CC1
CSEG
AT
2400H
_main:
Preprocessing
Function body
Post-processing
ret
EXAMPLE 2
The following is a code example in which the main C code is followed by a #pragma directive. The contents are
allocated in the section following "//".
#pragma section @@DATA ??DATA
int a1;
// ??DATA
sreg int b1;
// @@DATS
int c1 = 1;
// @@INIT and @@R_INIT
const int d1 = 1;
// @@CNST
#pragma section @@DATS ??DATS
int a2;
// ??DATA
sreg int b2;
// ??DATS
int c2 = 1;
// @@INIT and @@R_INIT
const int d2 = 1;
// @@CNST
#pragma section @@DATA ??DATA2
// ??DATA is automatically closed and ??DATA2 becomes valid
int a3;
// ??DATA2
370
sreg int b3;
// ??DATS
int c3 = 3;
// @@INIT and @@R_INIT
const int d3 = 3;
// @@CNST
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
(EXAMPLE 2 …continued)
#pragma section @@DATA @@DATA
// ??DATA2 is closed and processing returns to the default @@DATA
#pragma section @@INIT ??INIT
#pragma section @@R_INIT ??R_INIT
// ROMization is invalidated unless both names (@@INIT and @@R_INIT) are changed.
// This is the user's responsibility.
int a4;
// ??DATA
sreg int b4;
// ??DATS
int c4 = 1;
// ??INIT and ??R_INIT
const int d4 = 1;
// @@CNST
#pragma section @@INIT @@INIT
#pragma section @@R_INIT @@R_INIT
// ??INIT and ??R_INIT are closed and processing returns to the default setting
#pragma section @@BITS ??BITS
// ??BITS
_ _boolean e4;
#pragma section @@CNST ??CNST
// p and "Hello" are both ??CNST
char*const p = "Hello";
EXAMPLE 3
#pragma section @@INIT ??INIT1
#pragma section @@R_INIT ??R_INIT1
#pragma section @@DATA ??DATA1
char c1;
int i2;
#pragma section @@INIT ??INIT2
#pragma section @@R_INIT ??R_INIT2
#pragma section @@DATA ??DATA2
char c1;
int i2 = 1;
#pragma section @@DATA ??DATA3
#pragma section @@INIT ??INIT3
#pragma section @@R_INIT ??R_INIT3
extern char c1;
// ??DATA3
int i2;
// ??INIT3 and ??R_INIT3
#pragma section @@DATA ??DATA4
#pragma section @@INIT ??INIT4
#pragma section @@R_INIT ??R_INIT4
User’s Manual U14872EJ1V0UM
371
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
Restrictions when this #pragma directive has been specified after the main C code are explained in the following
coding error examples.
CODING ERROR EXAMPLE 1
a1.h
#pragma section @@DATA ??DATA1
// File containing only the #pragma section
a2.h
extern int func1 (void);
#pragma section @@DATA ??DATA2
// File containing the main C code followed by the #pragma
// directive
a3.h
#pragma section @@DATA ??DATA3
// File containing only the #pragma section.
a4.h
#pragma section @@DATA ??DATA3
extern int func2 (void);
// File that includes the main C code.
a.c
#include "a1.h"
#include "a2.h"
#include "a3.h"
// ← Results in an error.
// Because the a2.h file contains the main C code followed by this
// #pragma directive, file a3.h, which includes only this #pragma
// directive, cannot be included.
#include "a4.h"
372
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
CODING ERROR EXAMPLE 2
b1.h
const int i;
b2.h
const int j;
// This does not result in an error since it is not file (b.c) in which
#include "b1.h"
// the main C code is followed by this #pragma directive.
b.c
const int k;
#pragma section @@DATA ??DATA1
// ← Results in an error
#include "b2.h"
// Since an #include statement cannot be coded afterward in file
// (b.c) in which the main C code is followed by this #pragma
// directive.
CODING ERROR EXAMPLE 3
c1.h
extern int j;
#pragma section @@DATA ??DATA1
// This does not result in an error since the #pragma directive is
// included and processed before the processing of c3.h.
c2.h
extern int k;
#pragma section @@DATA ??DATA2
// ← Results in an error.
// This #include statement is specified after the main C code in
// c3.h, and the #pragma directive cannot be specified afterward.
c3.h
#include “c1.h”
extern int i;
#include “c2.h”
#pragma section @@DATA ??DATA3
// ← Results in an error.
// This #include statement is specified after the main C code, and
// the #pragma directive cannot be specified afterward.
c.c
#include “c3.h”
#pragma section @@DATA??DATA4
// ← Results in an error.
// This #include statement is specified after the main C code in
// c3.h, and the #pragma directive cannot be specified afterward.
int i;
User’s Manual U14872EJ1V0UM
373
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
COMPATIBILITY
<From another C compiler to this C compiler>
• The source program need not be modified if the section name change function is not supported.
• To change the section name, modify the source program according to the procedure described in USAGE
above.
<From this C compiler to another C compiler>
• Delete #pragma section ... or delimit it with #ifdef.
• To change the section name, modify the program according to the specifications of each compiler.
RESTRICTIONS
• A section name that indicates a segment for the vector table (e.g., @@VECT02, etc.) must not be changed.
• If two or more sections with the same name as the one specifying the AT start address exist in another file, a
link error occurs.
• When changing compiler output section names @@DATS, @@BITS, and @@INIS, limit the range of the
specified address within 0FE20H to 0FED7H.
CAUTION
• A section is equivalent to a segment of the assembler.
• The compiler does not check whether the new section name is duplicated with another symbol. Therefore,
the user must check to see whether the section name is not duplicated by assembling the output assemble
list.
• If a section name (*) related to ROMization is changed by using #pragma section, the startup routine must
be changed by the user on his/her own responsibility.
(*) ROMization-related section name
@@R_INIT, @@R_INIS, @@INIT, @@INIS
The startup routine to be used when a section related to ROMization is changed, and an example of changing
the end module are described later.
374
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
[Examples of Changing Startup Routine in Connection with Changing Section Name Related to ROMization]
Here are examples of changing the startup routine (cstart.asm or cstartn.asm) and end module (rom.asm) in
connection with changing a section name related to ROMization.
(C source)
#pragma section @@R_INIT RTT1
#pragma section @@INIT
TT1
If a section name that stores an external variable with an initial value has been changed by describing #pragma
section indicated above, the user must add to the startup routine the initial processing of the external variable to
be stored to the new section.
To the startup routine, therefore, add the declaration of the first label of the new section and the portion that
copies the initial value, and add the portion that declares the end label to the end module, as described below.
RTT1_S and RTT1_E are the names of the first and end labels of section RTT1, and TT1_S and TT1_E are the
names of the first and end labels of section TT1.
(Example of changing startup routine cstartx.asm)
<1> Add the declaration of the label indicating the end of the section with the changed name
.
.
.
EXTRN
_main,_exit,[email protected]
EXTRN
_?R_INIT,_?R_INIS,_?DATA,_?DATS
EXTRN
RTT1_E,TT1_E
←
Adds EXTRN declaration of RTT1_E and TT1_E
.
.
.
User’s Manual U14872EJ1V0UM
375
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
<2> Add a section to copy the initial values from the RTT1 section with the changed name to the TT1 section.
.
.
.
LDATS1:
MOVW
AX,HL
CMPW
AX,#_?DATS
BZ
$LDATS2
MOV
A,#0
MOV
[HL],A
INCW
HL
BR
$LDATS1
MOVW
DE,#TT1_S
MOVW
HL,#RTT1_S
MOVW
AX,HL
CMPW
AX,#RTT1_E
Adds section to copy the initial values from
BZ
$LTT2
the RTT1 section to the TT1 section
MOV
A,[HL]
MOV
[DE],A
INCW
HL
INCW
DE
BR
$LTT1
CALL
!_main
MOVW
AX,#0
CALL
!_exit
BR
$$
LDATS2:
LTT1:
LTT2:
;
; main();
; exit(0);
;
376
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
<3> Set the label of the start of the section with the changed name.
.
.
.
@@R_INIT
CSEG
[email protected]_INIT:
@@R_INIS
CSEG
UNITP
[email protected]_INIS:
@@INIT
DSEG
[email protected]:
@@DATA
DSEG
[email protected]:
@@INIS
DSEG
SADDRP
DSEG
SADDRP
[email protected]:
@@DATS
[email protected]:
; Indicates the start of the RTT1 section
; Adds the label setting
RTT1
CSEG
; Indicates the start of the TT1 section
RTT1_S:
TT1
; Adds the label setting
DSEG
TT1_S:
@@CALT
CSEG
@@CNST
CSEG
@@BITS
BSEG
CALLT0
;
END
User’s Manual U14872EJ1V0UM
377
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section…
#pragma section…
(Example of changing end module rom.asm)
(1) Add the declaration of the label indicating the end of the section with the changed name
NAME
@rom
;
PUBLIC
_?R_INIT,_?R_INIS
PUBLIC
_?INIT,_?DATA,_?INIS,_?DATS
PUBLIC
RTT1_E,TT1_E
←
Adds RTT1_E and TT1_E
;
@@R_INIT
CSEG
_?R_INIT:
@@R_INIS
CSEG
UNITP
_?R_INIS:
@@INIT
DSEG
_?INIT:
@@DATA
DSEG
_?DATA:
@@INIS
DSEG
SADDRP
DSEG
SADDRP
_?INIS:
@@DATS
_?DATS
.
.
.
(2) Setting the label indicating the end
.
.
.
RTT1
CSEG
; Adds the label setting
RTT1_E:
TT1
; Adds the label setting indicating the end of the RTT1 section.
DSEG
; Adds the label setting indicating the end of the TT1 section.
; Adds the label setting
TT1_E:
;
END
378
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(16) Binary constant
Binary Constant
Binary constant 0bxxx
FUNCTION
• Describes binary constants at the location where integer constants can be described.
EFFECT
• Constants can be described in bit strings without being replaced with an octal or hexadecimal number.
Readability is also improved.
USAGE
• Describe binary constants in the C source. The following shows the description method of binary constants.
0b binary number
0B binary number
Remark
Binary number: either ‘0’ or ‘1’
• A binary constant has 0b or 0B at the start and is followed by the list of numbers 0 or 1.
• The value of a binary constant is calculated with 2 as the base.
• The type of a binary constant is the first one that can express the value in the following list.
• Subscripted binary number:
int,
unsigned int,
long int
unsigned long int
• Subscripted u or U:
unsigned int,
unsigned long int
• Subscripted l or L:
long int
unsigned long int
• Subscripted u or U and subscripted l or L with:
unsigned long int
User’s Manual U14872EJ1V0UM
379
CHAPTER 11
EXTENDED FUNCTIONS
Binary Constant
Binary constant 0bxxx
EXAMPLE
(C source)
unsigned
i;
i = 0b11100101;
Output object of compiler is the same as the following case.
unsigned
i;
i = 0xE5;
COMPATIBILITY
<From another C compiler to this C compiler>
• Modifications are not needed.
<From this C compiler to another C compiler>
• Modifications are needed to meet the specifications of the compiler if the compiler supports binary constants.
• Modifications into other integer formats such as octal, decimal, and hexadecimal are needed if the compiler
does not support binary constants.
380
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(17) Module name changing function
Module Name Changing Function
#pragma name
FUNCTION
• Outputs the first eight letters of the specified module name to the symbol information table in a object module
file.
• Outputs the first eight letters of the specified module name to the assemble list file as symbol information
(MOD_NAM) when -G2 is specified and as the NAME quasi directive when -NG is specified.
• If a module name with nine or more letters is specified, a warning message is output.
• If unauthorized letters are described, an error occurs and the processing is aborted.
• If more than one of this #pragma directive exists, a warning message is output, and whichever directive is
described later is enabled.
EFFECT
• The module name of an object can be changed to any name.
USAGE
• The following shows the description method.
#pragma name module name
A module name must consist of the characters that the OS authorizes as a file name except ‘(‘ ‘)’. Upper case
and lowercase letters are distinguished.
EXAMPLE
#pragma name module1
.
.
.
COMPATIBILITY
<From another C compiler to this C compiler>
• Modifications are not needed if the compiler does not support the module name changing function.
• To change a module name, modifiy according to USAGE above.
<From this C compiler to another C compiler>
• Delete #pragma name . . . or delimit it with #ifdef.
• To change a module name, modify the program according to the specifications of each compiler.
User’s Manual U14872EJ1V0UM
381
CHAPTER 11
EXTENDED FUNCTIONS
(18) Rotate function
Rotate Function
#pragma rot
FUNCTION
• Outputs the code that rotates the value of an expression to the object with direct inline expansion instead of
function call and generates an object file.
• If there is no #pragma directive, the rotate function is regarded as an ordinary function.
EFFECT
• The rotate function can be realized by the C source or ASM description even if the processing to perform
rotate is not described.
USAGE
• Describe in the source in the same format as the function call.
The following four function names are
available for the rotate function.
rorb, rolb, rorw, rolw
[List of functions for rotate]
(a) unsigned char rorb (x, y) ;
unsigned char x ;
unsigned char y ;
Rotates x to the right y times.
(b) unsigned char rolb (x, y) ;
unsigned char x ;
unsigned char y ;
Rotates x to the left y times.
(c) unsigned int rorw (x, y) ;
unsigned int x ;
unsigned char y ;
Rotates x to the right y times.
(d) unsigned int rolw (x, y)
unsigned int x ;
unsigned char y ;
Rotates x to the left y times.
Caution
382
The above-mentioned function declaration is not affected by the -ZI option.
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Rotate Function
#pragma rot
• Declare the use of the function for rotate by the #pragma rot directive of the module.
However, the following items can be described before #pragma rot.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• Keywords following #pragma can be described in either uppercase or lowercase letters.
EXAMPLE
(C source)
#pragma rot
unsigned char a = 0x11 ;
unsigned char b = 2 ;
unsigned char c ;
void main ( ) {
c = rorb(a, b) ;
}
(Output assembler source)
mov
a,!_b
mov
c,a
mov
a,!_a
ror
a, 1
dbnz
c,$$-1
mov
!_c,a
RESTRICTIONS
• The function names for rotate cannot be used as function names.
• The function names for rotate must be described in lowercase letters. If the functions for rotate are described
in uppercase letters, they are handled as ordinary functions.
User’s Manual U14872EJ1V0UM
383
CHAPTER 11
EXTENDED FUNCTIONS
Rotate Function
#pragma rot
COMPATIBILITY
<From another C compiler to this C compiler>
• Modification is not needed if the compiler does not use the functions for rotate.
• To change to functions for rotate, modify according to USAGE above.
<From this C compiler to another C compiler>
• Delete the #pragma rot statement or delimit it with #ifdef.
• To use as a function for rotate, modify the program according to the specifications of each compiler (#asm,
#endasm or asm() ; , etc.).
384
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(19) Multiplication function
Multiplication Function
#pragma mul
FUNCTION
• Outputs the code that multiplies the value of an expression to the object with direct inline expansion instead of
function call and generates an object file.
• If there is no #pragma directive, the multiplication function is regarded as an ordinary function.
EFFECT
• Codes that are compatible with the CC78K0 and utilize the data size of the multiplication instruction I/O are
generated. Therefore, codes with a smaller size than the description of ordinary multiplication expressions
can be generated.
USAGE
• Describe in the same format as that of a function call in the source.
mulu
[List of multiplication functions]
unsigned int mulu (x, y) ;
unsigned char x ;
unsigned char y ;
Performs unsigned multiplication of x and y.
• Declare the use of functions for multiplication by the #pragma mul directive of the module.
However, the following items can be described before #pragma mul.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• Keywords following #pragma can be described in either uppercase or lowercase letters.
User’s Manual U14872EJ1V0UM
385
CHAPTER 11
EXTENDED FUNCTIONS
Multiplication Function
#pragma mul
RESTRICTIONS
• Multiplication functions are not expanded but are called by the library.
EXAMPLE
(C source)
#pragma mul
unsigned char a = 0x11 ;
unsigned char b = 2 ;
unsigned int i ;
void main()
{
i = mulu(a, b) ;
}
(Output object of compiler)
mov
a,!_b
mov
x,a
mov
a,!_a
callt [@@mulu]
movw
de,#_i
callt [@@deist]
COMPATIBILITY
<From another C compiler to this C compiler>
• Modifications are not needed if the compiler does not use the functions for multiplication.
• To change to functions for multiplication, modify according to USAGE above.
<From this C compiler to another C compiler>
• Function names for multiplication can be used as function names by deleting the #pragma mul statement or
delimiting it with #ifdef.
• To use as functions for multiplication, modify the program according to the specifications of each compiler
(#asm, #endasm or asm() ;, etc.).
386
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(20) Division function
Division Function
#pragma div
FUNCTION
• Outputs the code which divides the value of an expression from object with direct inline expansion instead of
function call and generates an object code file.
• If there is no #pragma directive, the function for division is regarded as an ordinary function.
EFFECT
• Codes that are compatible with the CC78K0 and utilize the data size of the division instruction I/O are
generated. Therefore, codes with a faster execution speed and smaller size than the description of ordinary
division expressions can be generated.
USAGE
• Describe in the same format as that of a function call in the source. The following two function names are
available for division.
divuw, moduw
List of division functions
(a) unsigned int divuw(x, y) ;
unsigned int x ;
unsigned char y ;
Performs unsigned division of x and y and returns the quotient.
(b) unsigned char moduw(x, y) ;
unsigned int x ;
unsigned char y ;
Performs unsigned division of x and y and returns the remainder.
Caution
The above-mentioned function declaration is not affected by the -ZI option.
• Declare the use of the functions for division by the #pragma div directive of the module.
However, the following items can be described before #pragma div.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• Keywords following #pragma can be described in either uppercase or lowercase letters.
User’s Manual U14872EJ1V0UM
387
CHAPTER 11
EXTENDED FUNCTIONS
Division Function
#pragma div
RESTRICTIONS
• The division functions are not expanded in line, but are called by the library.
EXAMPLE
(C source)
#pragma div
unsigned int a = 0x1234 ;
unsigned char b = 0x12 ;
unsigned char c ;
unsigned int i ;
void main () {
i = divuw(a, b) ;
c = moduw(a, b) ;
}
(Output object of compiler)
388
mov
a,!_b
mov
c,a
movw
de,#_a
callt
[@@deilo]
callt
[@@divuw]
movw
de,#_i
callt
[@@deist]
mov
a,!_b
mov
c,a
movw
de,#_a
callt
[@@deilo]
callt
[@@divuw]
mov
a,c
mov
!_c,a
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Division Function
#pragma div
COMPATIBILITY
<From another C compiler to this C compiler>
• Modification is not needed if the compiler does not use the functions for division.
• To change to functions for division, modify according to USAGE above.
<From this C compiler to another C compiler>
• The function names for division can be used as function names by deleting the #pragma div statement or
delimiting it with #ifdef.
• To use as a function for division, modify the program according to the specifications of each compiler (#asm,
#endasm or asm() ; , etc.).
User’s Manual U14872EJ1V0UM
389
CHAPTER 11
EXTENDED FUNCTIONS
(21) BCD operation function
BCD Operation Function
#pragma bcd
FUNCTION
• Outputs the code that performs a BCD operation on the expression value in an object by direct inline
expansion rather than by function call, and generates an object file.
• If there is no #pragma directive, the function for BCD operation is regarded as an ordinary function.
EFFECT
• Even if the process of the BCD operation is not described, the BCD operation function can be realized by the
C source or ASM statements.
USAGE
• The same format as that of a function call is coded in the source. There are 13 types of function names for
BCD operation, as listed below. Refer to List of functions for BCD operation, later in this chapter for more
information.
adbcdb, sbbcdb, adbcdbe, sbbcdbe, adbcdw, sbbcdw, adbcdwe,
sbbcdwe, bcdtob, btobcde, bcdtow, wtobcd, btobcd
• Use of functions for division is declared by the module’s #pragma bcd directive. However, the following items
can be coded before #pragma bcd.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• Either uppercase or lowercase letters can be used for keywords described after #pragma.
RESTRICTIONS
• BCD operation function names cannot be used as function names.
• The BCD operation function is coded in lowercase letters. If uppercase letters are used, these functions are
regarded as an ordinary functions.
• adbcdwe and sbbcdwe are not supported in the static model.
390
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
BCD Operation Function
#pragma bcd
EXAMPLE
(C source)
#pragma bcd
unsigned char a = 0x12 ;
unsigned char b = 0x34 ;
unsigned char c ;
void main ( )
{
c = adbcdb (a, b) ;
c = sbbcdb (b, a) ;
}
(Output assembler source)
mov
a, !_a
add
a, !_b
adjba
mov
!_c, a
mov
a, !_b
sub
a, !_a
adjbs
mov
!_c, a
[List of functions for BCD operation]
(1) unsigned char adbcdb (x, y) ;
unsigned char x ;
unsigned char y ;
Decimal addition is carried out by the BCD adjustment instruction.
(2) unsigned char sbbcdb (x, y) ;
unsigned char x ;
unsigned char y ;
Decimal subtraction is carried out by the BCD adjustment instruction.
User’s Manual U14872EJ1V0UM
391
CHAPTER 11
EXTENDED FUNCTIONS
BCD Operation Function
#pragma bcd
(3) unsigned int adbcdbe (x, y) ;
unsigned char x ;
unsigned char y ;
Decimal addition is carried out by the BCD adjustment instruction (with result expansion).
(4) unsigned int sbbcdbe (x, y) ;
unsigned char x ;
unsigned char y ;
Decimal subtraction is carried out by the BCD adjustment instruction (with result expansion). If a borrow occurs,
the higher digits are set to 0x99.
(5) unsigned int adbcdw (x, y) ;
unsigned int x ;
unsigned int y ;
Decimal addition is carried out by the BCD adjustment instruction.
(6) unsigned int sbbcdw (x, y) ;
unsigned int x ;
unsigned int y ;
Decimal subtraction is carried out by the BCD adjustment instruction.
(7) unsigned long adbcdwe (x, y) ;
unsigned int x ;
unsigned int y ;
Decimal addition is carried out by the BCD adjustment instruction (with result expansion).
(8) unsigned long sbbcdwe (x, y) ;
unsigned int x ;
unsigned int y ;
Decimal subtraction is carried out by the BCD adjustment instruction (with result expansion). If a borrow occurs,
the higher digits are set to 0x9999.
(9) unsigned char bcdtob (x) .
unsigned char x ;
Decimal numbers are converted to binary numbers.
(10) unsigned int btobcde (x) ;
unsigned char x ;
Binary numbers are converted to decimal numbers.
392
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
BCD Operation Function
#pragma bcd
(11) unsigned int bcdtow (x) ;
unsigned int x ;
Decimal numbers are converted to binary numbers.
(12) unsigned int wtobcd (x) ;
unsigned int x ;
Decimal numbers are converted to binary numbers. However, if the value of x exceeds 10000, 0xffff is returned.
(13) unsigned char btobcd (x) ;
unsigned char x ;
Decimal numbers are converted to binary numbers. However, the overflow is discarded.
Caution The above-mentioned function declarations are not influenced by the -ZI and -ZL options.
COMPATIBILITY
<From another C compiler to this C compiler>
• Modification is not needed if functions for BCD operations are not used.
• To change another function to the function for BCD operation, modify according to USAGE above.
<From this C compiler to another C compiler>
• A BCD operation function name can be used as a function name by deleting the #pragma bcd statement or
delimiting it with #ifdef.
• To use pragma bcd as a BCD operation function, modify the program according to the specifications of each
compiler (#asm, #endasm or asm(); etc.).
User’s Manual U14872EJ1V0UM
393
CHAPTER 11
EXTENDED FUNCTIONS
(22) Data insertion function
Data Insertion Function
#pragma opc
FUNCTION
• Inserts constant data into the current address.
• When there is no #pragma directive, the function for data insertion is regarded as an ordinary function.
EFFECT
• Specific data and instructions can be embedded in the code area without using the ASM statement.
When ASM is used, an object cannot be obtained without going through the assembler, whereas if the data
insertion function is used, an object can be obtained without going through the assembler.
USAGE
• Describe using uppercase letters in the source in the same format as that of a function call.
• The function name for data insertion is _ _OPC.
[List of data insertion functions]
void _ _OPC (unsigned char x,…);
Insert the value of the constant described in the argument to the current address.
Arguments can describe only constants.
• Declare the use of functions for data insertion by the #pragma opc directive.
However, the following items can be described before #pragma opc.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
• Keywords following #pragma can be described in either uppercase or lowercase letters.
RESTRICTIONS
• The function names for data insertion cannot be used as function names (when #opc is specified).
• _ _OPC must be described in uppercase letters. If it is described in lowercase letters, it is handled as an
ordinary function.
394
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Data Insertion Function
#pragma opc
EXAMPLE
(C source)
#pragma opc
void main ( ) {
_ _OPC(0xBF) ;
_ _OPC(0xA1, 0x12) ;
_ _OPC(0x10, 0x34, 0x12) ;
}
(Output object of compiler)
_main :
; line
DB
; line
4 : _ _OPC (0xBF) ;
0BFH
5 : _ _OPC (0xA1, 0x12) ;
DB
0A1H
DB
012H
; line
6 : _ _OPC (0x10, 0x34, 0x12) ;
DB
010H
DB
034H
DB
012H
; line
7 : }
ret
COMPATIBILITY
<From another C compiler to this C compiler>
• Modification is not needed if the compiler does not use the functions for data insertion.
• To change to functions for data insertion, modify according to USAGE above.
<From this C compiler to another C compiler>
• Function names for data insertion can be used as function names by deleting the #pragma opc statement or
delimiting it with #ifdef.
• To use as a function for data insertion, modify the program according to the specifications of each C compiler
(#asm, #endasm or asm() ; , etc.).
User’s Manual U14872EJ1V0UM
395
CHAPTER 11
EXTENDED FUNCTIONS
(23) Static model
Static Model
FUNCTION
• All arguments are passed through registers (Refer to 11.7.5 Static model function call interface).
• Function arguments that are passed through registers are allocated in the function-specific static area.
• Automatic variables are allocated to the function-specific static area.
• In the case of the leaf function
Note
, arguments and automatic variables are allocated to the saddr area below
0FEFFH, in the order of description starting from the higher addresses. Since the saddr area is commonly
used by the leaf functions of all modules, this area is referred to as the shared area. The maximum size of the
shared area is defined by the parameter when the -SM option is specified.
-SM [nn]: nn = 0 to 16
nn bytes are assigned as shared area and the rest are allocated to the function-specific static area. If nn = 00
is specified or this specification is omitted, the shared area is not used.
Note For the functions that do not call functions, it is not necessary to describe norec/_ _leaf since the
compiler executes automatic determination.
• It is possible to add the sreg/_ _sreg keywords to function arguments and automatic variables. Function
arguments and automatic variables that have the sreg/_ _sreg keywords added are allocated to the saddr
area. As a result, bit manipulation becomes possible.
• By specifying the -RK option, function arguments and automatic variables (except for the static variables in
functions) are allocated to saddr and bit manipulation becomes possible (Refer to 11.5 (3) How to use the
saddr area).
• The compiler executes the following macro definition automatically.
#define _ _STATIC_MODEL_ _ 1
EFFECT
• Normally, instructions that access the static area are shorter and faster than those that access static frames.
Accordingly, it is possible to shorten object codes and increase execution speed.
• The save/restore processing of arguments and variables that use the saddr area (register variables in
interrupt functions, norec function argument/automatic variables, runtime library arguments) is not performed,
as a result, it is possible to increase the speed of interrupt processing.
• Memory space can be saved since the data area is commonly used by several leaf functions.
USAGE
• Specify the -SM option during compilation.
The object in this case is called the static model, while the object without specification of the -SM option is
called normal model.
396
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model
EXAMPLE
An example of the -SM4 specification is as follows.
(C source)
void sub (char, char, char) ;
void main ()
{
char i = 1 ;
char j, k ;
j = 2 ;
k = i + j ;
sub (i, j, k) ;
}
void sub (char p1, char p2, char p3)
{
char a1, a2 ;
a1 = 1<<p1 ;
a2 = p2 + p3 ;
}
(Output object of compiler)
@@DATA
DSEG
!L0003: DS
(1)
; Automatic variable i of function main
!L0004: DS
(1)
; Automatic variable j of function main
!L0005: DS
(1)
; Automatic variable k of function main
!L0008: DS
(1)
; Automatic variable a2 of function sub
; line
1: void sub (char, char, char) ;
; line
2: void main ()
; line
3: {
@@CODE
CSEG
_main:
; line
4 : char i = 1 ;
mov
mov
; line
a,#01H
!?L0003,a
;1
;i
; Automatic variable i
5: char j, k ;
User’s Manual U14872EJ1V0UM
397
CHAPTER 11
EXTENDED FUNCTIONS
Static Model
(Output object of compiler …continued)
;line
6 : j = 2 ;
inc
a
mov
!?L0004,a
; line
;j
; Automatic variable j
7 : k = i + j ;
add
a, !?L0003
;i
; Add i and j
mov
!?L0005, a
;k
; Substitute for k
; line
8 : sub (i, j, k) ;
mov
hl, ax
mov
a, !?L0004
movw
bc, ax
movw
a, !?L0003
call
!_sub
; line
; Passes k through register H
;j
; Passes j through register B
;i
; Passes i through register A
9 : }
ret
; line
10 : void sub (char p1, char p2, char p3)
; line
11 : {
_sub:
mov
[email protected], a
movw
ax, bc
mov
[email protected], a
movw
ax, hl
mov
[email protected], a
; line
12 : char a1, a2 ;
; line
13 : a1 = p1 ;
; Allocates the 1st argument to the shared area
; Allocates the 2nd argument to the shared area
; Allocates the 3rd argument to the shared area
mov
a,[email protected]
;p1
; 1st argument p1
mov
[email protected], a
;a1
; Automatic variable a1 is the shared area
; line
14 : a2 = p2 + p3 ;
mov
a,[email protected]
;p2
; 2nd argument p2
add
a,[email protected]
;p3
; Adds 3rd argument p3
mov
!?L0008, a
;a2
; Automatic variable a2 is in the specific function area
; line
15 : }
ret
398
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model
RESTRICTIONS
• Static model modules cannot be linked with a modules of a normal model. However, static model modules
can be linked to each other even if the maximum size of the shared area is different.
• Floating-point numbers are not supported. If the float and double keywords are described, a fatal error
occurs.
• Arguments are limited to a maximum of 3 arguments and 6 bytes in total.
• It is impossible to use variable length arguments since arguments are not passed through stacks. Using
variable length arguments causes an error.
• Arguments and return values of structures/unions cannot be used. The description of these arguments and
values causes an error.
• The noauto/norec/_ _leaf functions cannot be used. A warning message is output and the descriptions are
ignored (Refer to 11.5 (5) noauto functions, 11.5 (6) norec functions).
• Recursive functions cannot be used. As function arguments and the automatic variable area are statically
secured, recursive functions cannot be used. An error is generated for recursive functions that can be
detected by the compiler.
• A prototype declaration cannot be omitted. An error is generated if neither the function’s real definition nor a
prototype declaration exist, in spite of there being a function call.
• Due to the restrictions of arguments and inability to use recursive functions, some standard libraries cannot
be used.
• If the -ZL option has not been specified, a warning is output and processing is carried out as if the -ZL option
was specified. long types are therefore always regarded as int types (see 11.5 (24) Type modification).
COMPATIBILITY
<From another C compiler to this C compiler>
• When creating objects of normal model, source modification is not needed unless the -SM option is specified.
• To create a static model object, modifications are made according to USAGE above.
<From this C compiler to another C compiler>
• Source modification is not needed if re-compiling is performed by another compiler.
CAUTIONS
• Since arguments/automatic variables are secured statically, the contents of arguments/automatic variables in
recursive functions may be destroyed. An error occurs when the function calls itself directly. However, no
error occurs when the function calls itself after an other function is called since the compiler cannot detect this
processing.
• During an interruption, the contents of arguments/automatic variables may be destroyed if the function being
processed is called by interrupt servicing (interrupt functions and functions that are called by interrupt
functions).
• During an interruption, save/restore of the shared area is not executed even when the functions being
processed are using the shared area.
User’s Manual U14872EJ1V0UM
399
CHAPTER 11
EXTENDED FUNCTIONS
(24) Type modification
Type Modification
-ZI
(1) Change from int/short type to char type
FUNCTION
• int and short types are regarded as char type. In other words, int and short descriptions become equal to a
char description.
• Details of the type modification are given as follows (some are affected by the -QU options).
Table 11-13. Details of Type Modification (Change from int and short Type to char Type)
Type Described in C Source
Option
Type after Modification
short, short int, int
With -QU
unsigned char
short, short int, int
Without -QU
signed char
unsigned short, unsigned short int,
unsigned, unsigned int
−
unsigned char
signed short, signed short int,
signed, signed int
−
signed char
• Outputs warning message to the line where the int or short keywords first appeared in C source.
• The -QC option becomes valid regardless of whether it is specified. A warning message is output when there
is no -QC option specification, and the -QC option becomes valid.
• If the -ZA option is specified at the same time (such as the -ZAI option), a warning message is output (only
when -W2 is specified).
• The following statements can be described by a type specifier and omitted, so are regarded as char type.
• Arguments and returned values of functions
• Type specifier omitted variables/function declaration
• The compiler executes the following macro definition automatically.
#define _ _FROM_INT_TO_CHAR_ _ 1
• Some standard libraries cannot be used.
USAGE
• The -ZI option is specified.
RESTRICTIONS
• -ZI specified and -ZI unspecified modules cannot be linked together.
400
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Type Modification
-ZL
(2) Change from long type to int type
FUNCTION
• long type is regarded as int type. In other words, a long description becomes equal to an int description.
• Details of the type modification are given as follows.
Table 11-14. Details of Type Modification (Change from long Type to int Type)
Type Described in C Source
Type after Modification
unsigned long, unsigned long int
unsigned int
long, long int, signed long, signed long int
signed int
• Outputs warning message to the line where the long keyword first appeared in C source.
• If the -ZA option is specified at the same time (-ZAL), a warning message is output (only when -W2 is
specified).
• The compiler executes the following macro definition automatically.
#define _ _FROM_LONG_TO_INT_ _ 1
• Some standard libraries cannot be used.
USAGE
• Specify the -ZL option.
RESTRICTIONS
• -ZL specified and -ZL unspecified modules cannot be linked together.
User’s Manual U14872EJ1V0UM
401
CHAPTER 11
EXTENDED FUNCTIONS
(25) Pascal function
Pascal Function
_ _pascal
FUNCTION
• Generates the code that corrects the stack used for placing arguments during the function call on the called
function side, not on the side calling the function.
EFFECT
• Object code can be shortened if function calls appear in many places.
USAGE
• When a function is declared, add a _ _pascal attribute to the beginning.
RESTRICTIONS
• The pascal function does not support variable length arguments. If a variable length argument is defined, a
warning is output and the _ _pascal keyword is ignored.
• The keywords norec/_ _interrupt cannot be specified in a pascal function. If they are specified, in the case of
the norec keyword, the _ _pascal keyword is ignored and in the case of the _ _interrupt/_ _interrupt_brk/
_ _rtos_interrupt keywords, an error is output.
• If a prototype declaration is incomplete, normal operation may not be possible, so a warning message is
output when a pascal function’s physical definition or prototype declaration is missing.
• Pascal functions are not supported when the static model specification option (-SM) is specified. If -SM is
specified when using the pascal function, a warning message is output to the place where the _ _ pascal
keyword first appeared, and the _ _ pascal keyword in the input file is ignored.
EXPLANATION
• The -ZR option enables the change of all functions to the pascal function. However, if the pascal function is
used for functions that have few calls, the object code may increase.
402
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Pascal Function
_ _pascal
EXAMPLE
(C source)
_ _pascal int func(int a, int b, int c);
void main()
{
int ret_val;
ret_val = func(5, 10, 15);
}
_ _pascal int func(int a, int b, int c);
{
return (a + b + c);
}
(Output object of compiler)
_main:
push
hl
movw
ax, #02H
callt
[[email protected]]
; 15
movw
ax, #0FH
push
ax
mov
x, #0AH
push
ax
mov
x, #05H
call
!_func
movw
ax, bc
; The stack is not modified here.
mov
[h1+1], a
; ret_val
xch
a, x
mov
[hl],a
pop
ax
pop
hl
; 10
;5
; ret_val
ret
User’s Manual U14872EJ1V0UM
403
CHAPTER 11
EXTENDED FUNCTIONS
Pascal Function
_ _pascal
(Output object of compiler …continued)
_func:
push
hl
push
ax
movw
ax, sp
movw
hl, ax
mov
a, [hl]
;a
mov
a, [hl + 6]
;b
xch
a, x
mov
a, [hl + 1]
;a
addc
a, [hl + 7]
;b
xch
a, x
add
a, [hl + 8]
xch
a, x
addc
a, [hl + 9]
movw
bc, ax
pop
ax
pop
hl
pop
de
; Obtains the return address
pop
ax
;
pop
ax
; Modifies the 4-byte stack consumed by the caller
push
de
; Reloads return address
;c
;c
COMPATIBILITY
<From another C compiler to this C compiler>
• If the reserved word, _ _ pascal is not used, modification is not required.
• To change to the Pascal function, modify according to USAGE above.
<From this C compiler to another C compiler>
• Compatibility is maintained by using #define.
• By this conversion, the pascal function is regarded as an ordinary function.
404
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(26) Automatic pascal functionization of function call interface
Automatic Pascal Functionization of Function Call Interface
-ZR
FUNCTION
• With the exception of norec/_ _interrupt/ variable length argument functions, _ _pascal attributes are added
to all functions.
USAGE
• Specify the -ZR option during compilation.
RESTRICTIONS
• Modules in which the -ZR option is specified and modules in which the -ZR option is not specified cannot be
linked. If a link is executed, it results in a link error.
• It is impossible to specify the static model specification option (-SM) and the -ZR option at the same time. If
specified, a warning message is output and the -ZR option is ignored.
• Since the mathematical function standard library does not support the pascal function, the -ZR option cannot
be used when the mathematical function standard library is used.
Remark
For details of the pascal function call interface, refer to 11.7.6 Pascal function call interface.
User’s Manual U14872EJ1V0UM
405
CHAPTER 11
EXTENDED FUNCTIONS
(27) Method of int expansion limitation of argument/return value
Method of int Expansion Limitation of Argument/Return Value
-ZB
FUNCTION
• When the type definition of the function return value is char/unsigned char, the int expansion code of the
return value is not generated.
• When the prototype of the function argument is defined and the argument definition of the prototype is
char/unsigned char, the int expansion code of the argument is not generated.
EFFECT
• The object code can be reduced and the execution speed improved since the int expansion codes are not
generated.
USAGE
• The -ZB option is specified during compilation.
EXAMPLE
(C source)
unsigned char func1(unsigned char x, unsigned char y);
unsigned char c, d, e;
void main()
{
c = func1(d, e);
c = func2(d, e);
}
unsigned char func1(unsigned char x, unsigned char y)
{
return x + y;
}
(Output object of compiler)
When -ZB is specified
_main:
; line 5:
406
c = func1 (d, e) ;
mov
a, !_e
xch
a, x
push
ax
mov
a, !_d
xch
a, x
call
!_func1
; int expansion is not executed
; int expansion is not executed
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Method of int Expansion Limitation of Argument/Return Value
-ZB
(Output object of compiler) (continued)
pop
ax
mov
a, c
mov
!_c, a
; line
6: c = func2 (d, e) ;
mov
a, !_e
xch
a, x
xor
a, a
push
ax
mov
a, !_d
xch
a, x
xor
a, a
call
!_func2
pop
ax
mov
a, c
mov
!_c, a
; line
; Executes int expansion since there is no prototype declaration
; Executes int expansion since there is no prototype declaration
7: }
ret
; line
8:
; line
9: unsigned char func1 (unsigned char x, unsigned char y){
_func1:
push
hl
push
ax
movw
ax, sp
movw
hl, ax
; line
10: return x+y;
mov
a, [hl];x
add
a, [hl+6];y
mov
c, a
; line
11: }
pop
ax
pop
hl
ret
END
User’s Manual U14872EJ1V0UM
407
CHAPTER 11
EXTENDED FUNCTIONS
Method of int Expansion Limitation of Argument/Return Value
-ZB
RESTRICTIONS
• If the files are different between the definition of the function body and the prototype declaration to this
function, the program may operate incorrectly.
COMPATIBILITY
<From another C compiler to this C compiler>
• If the prototype declarations for all definitions of function bodies are not correctly performed, perform correct
prototype declaration. Alternatively, do not specify the -ZB option.
<From this C compiler to another C compiler>
• No modification is needed.
408
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(28) Array offset calculation simplification method
Array Offset Calculation Simplification Method
-QW2, -QW3, -QW4, -QW5
FUNCTION
• When calculating the offset of char/unsigned char/unsigned int/short/unsigned short types and the index
is an unsigned char-type variable, a code to calculate only lower bytes is generated based on the
presumption that there is no carry-over.
• When the -QW2 option is specified, a code to calculate only lower bytes for the offset is generated with a
speed-based priority only when referencing the sequence of the saddr area configuration with an unsigned
char variable.
• When the -QW3 option is specified, the code to calculate only lower bytes for the offset is generated with a
speed-based priority when referencing the sequence with an unsigned char variable regardless of the
configured area.
• When the -QW4 option is specified, a code to calculate only lower bytes for the offset is generated with a
size-based priority only when referencing the sequence of the saddr area configuration with an unsigned
char variable.
• When the -QW5 option is specified, a code to calculate only lower bytes for the offset is generated with a
size-based priority when referencing the sequence with an unsigned char variable regardless of the
configured area.
EFFECT
• Realizes object code reduction and execution speed improvement since the offset calculation code is
simplified.
USAGE
• Specify the -QW2, -QW3, -QW4, and -QW5 options during compilation.
EXAMPLE
(C source)
unsigned char c ;
unsigned char ary [10] ;
sreg unsigned char sary [10] ;
void main ()
{
unsigned char a ;
a = ary [c] ;
a = sary [c] ;
}
User’s Manual U14872EJ1V0UM
409
CHAPTER 11
EXTENDED FUNCTIONS
Array Offset Calculation Simplification Method
-QW2, -QW3, -QW4, -QW5
(Output of compiler object)
When -QW3 is specified
_main :
push
hl
push
ax
movw
ax, sp
movw
hl, ax
; line
6 : unsigned char a ;
; line
7 :
; line
8 : a = ary [c] ;
mov
a, !_c
add
a, #low (_ary)
mov
e, a
mov
d, #high (_ary)
mov
a, [de]
mov
[hl + 1], a
; line
; Calculates only lower bytes
;a
9 : a = sary [c] ;
mov
a, !_c
add
a, #low (_sary)
mov
e, a
mov
d, #0FEH ; 254
mov
a, [de]
mov
; line
; Calculates only lower bytes
;a
[hl + 1], a
10 : }
pop
ax
pop
hl
ret
RESTRICTIONS
• If the configuration addresses of the sequence that is the target for offset calculation simplification is over the
border of 256 bytes, the program may operate incorrectly.
COMPATIBILITY
<From another C compiler to this C compiler>
• Assign the layout so that it does not exceed 256 bytes. Alternatively, do not specify the -QW2, -QW3, -QW4
and -QW5 options.
<From this C compiler to another C compiler>
• No modification is needed.
410
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(29) Register direct reference function
Register Direct Reference Function
#pragma realregister
FUNCTION
• Outputs the code that accesses the object register with direct inline expansion instead of function call, and
generates an object file.
• When there is no #pragma directive, the register direct reference function is regarded as an ordinary function.
EFFECT
• Due to the C description, register access can be performed easily.
USAGE
• This function is described in the same format as a function call (Refer to Register direct reference function
list later in this chapter).
There are 21 types of register direct reference function names.
_ _geta, _ _seta, _ _getax, _ _setax, _ _getcy, _ _setcy, _ _set1cy, _ _clr1cy
_ _not1cy, _ _inca, _ _deca, _ _rora, _ _rorca, _ _rola, _ _rolca, _ _shla
_ _shra, _ _ashra, _ _nega, _ _coma, _ _absa
• Use of the register direct reference function is declared by using the #pragma realregister directive in a
module.
However, the following items can be described before the #pragma realregister directive.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
EXAMPLE
(C source)
#pragma realregister
unsigned char c = 0x88,
d, e ;
void main ()
{
_ _seta (c) ;
/* Sets the variable of C in A register
*/
_ _shla () ;
/* Logically shifts 1 bit to left
*/
d = _ _geta () ;
/* Sets the value of A register in variable d */
if (_ _getcy () ) {
/* Refers CY (checks overflow)
*/
/* Sets e to 1 when CY = = 1
*/
e = 1 ;
}
}
User’s Manual U14872EJ1V0UM
411
CHAPTER 11
EXTENDED FUNCTIONS
Register Direct Reference Function
#pragma realregister
(Output object of compiler)
_main :
; line
5 : _ _seta (c) ;
mov
; line
add
/* Logically shift 1 bit to left
*/
a, a
7 : d = _ _geta () ;
mov
*/
a, !_c
6 : _ _shla () ;
; line
/* Sets the variable of C in A register
/* Sets value of A register in variable d */
!_d, a
8 : if (_ _getcy () ) {/* Refers CY (checks overflow)
; line
bnc
; line
$?L0003
e = 1 ; /* Sets e to 1 when CY = = 1
9
mov
a, #01H
mov
!_e, a
; 1
?L0003 :
; line
10 : }
; line
11 : }
ret
[Register direct reference function list]
(1) unsigned char
_ _geta (void) ;
Obtains the value of the A register.
(2) void
_ _seta (unsigned char x) ;
Sets x in the A register.
(3) unsigned int
_ _getax (void) ;
Obtains the value of the AX register.
(4) void
_ _setax (unsigned int x) ;
Sets x in the AX register.
(5) bit
_ _getcy (void) ;
Obtains the value of the CY flag.
(6) void
_ _setcy (unsigned char x) ;
Sets the lower 1 bit of x in the CY flag.
(7) void
_ _set1cy (void) ;
Generates the set1 CY instruction.
412
*/
User’s Manual U14872EJ1V0UM
*/
CHAPTER 11
EXTENDED FUNCTIONS
Register Direct Reference Function
(8) void
#pragma realregister
_ _clr1cy (void) ;
Generates the clr1 CY instruction.
(9) void
_ _not1cy (void) ;
Generates the not1 CY instruction.
(10) void
_ _inca (void) ;
Generates the inc a instruction.
(11) void
_ _deca (void) ;
Generates the dec a instruction.
(12) void
_ _rora (void) ;
Generates 1 ror a, instruction.
(13) void
_ _rorca (void) ;
Generates 1 rorc a, instruction.
(14) void
_ _rola (void) ;
Generates 1 rol a, instruction.
(15) void
_ _rolca (void) ;
Generates 1 rolc a, instruction.
(16) void
_ _shla (void) ;
Generates the code that performs logical-shift of the A register 1 bit to the left.
(17) void
_ _shra (void) ;
Generates the code that performs a logical-shift of the A register 1 bit to the right.
(18) void
_ _ashra (void) ;
Generates the code that performs an arithmetic-shift of the A register 1 bit to the right.
(19) void
_ _nega (void) ;
Generates the code that obtains 2’s complement in the A register.
(20) void
_ _coma (void) ;
Generates the code that obtains 1’s complement in the A register.
(21) void
_ _absa (void) ;
Generates the code that obtains the absolute value of the A register.
User’s Manual U14872EJ1V0UM
413
CHAPTER 11
EXTENDED FUNCTIONS
Register Direct Reference Function
#pragma realregister
RESTRICTIONS
• The function name of a register direct reference cannot be not used as a function name. The register direct
reference function is described in lowercase letters. A function described in uppercase letters are regarded as
an ordinary function.
• The values of the A and AX registers and CY flag that are set by the _ _ seta, _ _setax, and _ _setcy
functions are not retained in the next code generation.
• The timing that is referenced by the A and AX registers and CY flag with the _ _ geta, _ _getax, and _
_getcy functions, corresponds to the evaluation sequence of the expression.
COMPATIBILITY
<From another C compiler to this C compiler>
• If the register direct reference function is not used, modification is not necessary.
• To change to the register direct referencing function, modify according to USAGE above.
<From this C compiler to another C compiler>
• Register direct reference function names can be used as function names by deleting the #pragma
realregister directive or delimiting #ifdef.
• To use pragma realregister as a register direct reference function, modify the program according to the
specifications of each C compiler (#asm, #endasm, or asm();, etc.).
CAUTION
• There is no guarantee that CY, A, AX will be saved as intended before the register direct reference function is
executed. Accordingly, it is recommended to use this function before values change by describing it in the first
term of the expression.
414
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(30) Memory manipulation function
Memory Manipulation Function
#pragma inline
FUNCTION
• An object file is generated by the output of the standard library memory manipulation functions memcpy and
memset with direct inline expansion instead of function call.
• When there is no #pragma directive, the code that calls the standard library functions is generated.
EFFECT
• Compared with when a standard library function is called, the execution speed is improved.
• Object code is reduced if a constant is specified for the specified character number.
USAGE
• The function is described in the source in the same format as a function call.
• The following items can be described before #pragma inline.
• Comments
• Other #pragma directives
• Preprocessing directives that neither define nor reference variables or functions
EXAMPLE
(C source)
#pragma inline
char ary1[100], ary2[100];
void main()
{
memset(ary1, ‘A’, 50);
memcpy(ary1, ary2, 50);
}
User’s Manual U14872EJ1V0UM
415
CHAPTER 11
EXTENDED FUNCTIONS
Memory Manipulation Function
(Output object of compiler)
When -SM is not specified
_main:
push
;line
;line
;line
5:
hl
memset(ary1, ‘A’, 50);
movw
de,#_ary1
mov
a, #041H
; 65
mov
c, #032H
; 50
mov
[de], a
incw
de
dbnz
c, $$-2
6:
memcpy(ary1, ary2, 50);
movw
de, #_ary1
movw
hl, #_ary2
mov
c, #032H
mov
a, [hl]
mov
[de], a
incw
de
incw
hl
dbnz
c, $$-4
7:
pop
; 50
}
hl
ret
416
User’s Manual U14872EJ1V0UM
#pragma inline
CHAPTER 11
EXTENDED FUNCTIONS
Memory Manipulation Function
#pragma inline
When -SM is specified
_main:
push
;line
;line
;line
5:
de
memset(ary1, ‘A’, 50);
movw
hl,#_ary1
mov
a, #041H
; 65
mov
c, #032H
; 50
mov
[hl], a
incw
hl
dbnz
c, $$-2
6:
memcpy(ary1, ary2, 50);
movw
hl, #_ary1
movw
de, #_ary2
mov
c, #032H
mov
a, [de]
mov
[hl], a
incw
de
incw
hl
dbnz
c, $$-4
7:
pop
; 50
}
de
ret
COMPATIBILITY
<From another C compiler to this C compiler>
• Modification is not needed if the memory manipulation function is not used.
• When changing the memory manipulation function, modify according to USAGE above.
<From this C compiler to another C compiler>
• Delete the #pragma inline directive or delimit it with #ifdef.
User’s Manual U14872EJ1V0UM
417
CHAPTER 11
EXTENDED FUNCTIONS
(31) Absolute address allocation specification
Absolute Address Allocation Specification
_ _directmap
FUNCTION
• The initial value of an external variable declared by _ _directmap and a static variable in a function is
regarded as the allocation address specification, and variables are allocated to the specified addresses.
• The _ _directmap variable in the C source is treated as an ordinary variable.
• Because the initial value is regarded as the allocation address specification, the initial value cannot be
defined and remains an undefined value.
• The specifiable address specification range, secured area range linked by the module for securing the area
for the specified addresses, and variable duplication check range are shown below.
Address Specification Range
Secured Area Range
Duplication Check Range
0x80 to 0xffff
0xfd00 to 0xfeff
0xf000 to 0xfeff
• If the address specification is outside the address specification range, an F799 error is output.
• If the allocation address of a variable declared by _ _directmap is duplicated and is within the duplication
check range, a W762 warning message is output and the name of the duplicated variable is displayed.
• If the address specification range is inside the saddr area, the _ _sreg declaration is made automatically and
the saddr instruction is generated.
• If char/unsigned char/short/unsigned short/int/unsigned int/long/unsigned long type variables declared
by _ _directmap are bit referenced, sreg/_ _sreg must be specified along with _ _directmap. If they are not,
an error occurs.
EFFECT
One or more variables can be allocated to the same arbitrary address.
418
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Allocation Specification
_ _directmap
USAGE
• Declare _ _directmap in the module in which the variable to be allocated in an absolute address is to be
defined.
_ _directmap Type name Variable name
_ _directmap static
Type name
Variable name
_ _directmap _ _sreg Type name
Variable name
_ _directmap _ _sreg
Type name
static
= Allocation address specification;
= Allocation address specification;
= Allocation address specification;
Variable name = Allocation address specification;
• If _ _directmap is declared for a structure/union/array, specify the address in braces {}.
• _ _directmap does not have to be declared in a module in which a _ _directmap external variable is
referenced, so only declare extern.
extern Type name Variable name;
extern _ _sreg Type name
Variable name;
• To generate the saddr instruction in a module in which a _ _directmap external variable allocated inside the
saddr area is referenced, _ _sreg must be used together to make extern_ _sreg Type name Variable name;.
EXAMPLE
(C source)
_ _directmap char c = 0xfe00;
_ _directmap _ _sreg char d = 0xfe20;
_ _directmap _ _sreg char e = 0xfe21;
_ _directmap struct x {
char a;
char b;
} xx = {0xfe30};
void main()
{
c = 1;
d = 0x12;
e.5 = 1;
xx.a = 5;
xx.b = 10;
}
User’s Manual U14872EJ1V0UM
419
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Allocation Specification
_ _directmap
(Output object)
_c
PUBLIC
_c
PUBLIC
_d
PUBLIC
_e
PUBLIC
_xx
PUBLIC
_main
EQU
0FE00H
; Addresses for variables declared by _ _directmap
_d
EQU
0FE20H
; are defined by EQU
_e
EQU
0FE21H
;
_xx
EQU
0FE30H
;
EXTRN
_ _mmfe00
; EXTRN output for linking secured area modules
EXTRN
_ _mmfe20
;
EXTRN
_ _mmfe21
;
EXTRN
_ _mmfe30
;
EXTRN
_ _mmfe31
;
@@CODE CSEG
_main:
;line
;line
10:
a,#01H ;1
mov
!_c,a
11:
mov
;line
12:
set1
;line
13:
mov
;line
14:
mov
;line
c = 1;
mov
15:
d = 0x12;
_d,#012H
; saddr instruction output because address specified in saddr area
e.5 = 1;
_e.5
; Bit manipulation possible because _ _sreg also used
xx.a = 5;
_xx,#05H
; saddr instruction output because address specified in saddr area
xx.b = 10;
_xx+1,#0AH
; saddr instruction output because address specified in saddr area
}
ret
420
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Allocation Specification
_ _directmap
RESTRICTIONS
• _ _directmap cannot be specified for function arguments, return values, or automatic variables.
If it is
specified in these cases, an error occurs.
• If short/unsigned short/int/unsigned int/long/unsigned long type variables are allocated to odd
addresses, the correct code will be generated in the file declared by _ _directmap, but illegal code will be
generated if these variables are referenced by an extern declaration from an external file.
• If an address outside the secured area range is specified, the variable area will not be secured, making it
necessary to either describe a directive file or create a separate module for securing the area.
COMPATIBILITY
<From another C compiler to this C compiler>
• No modification is necessary if the keyword _ _directmap is not used.
• To change to the _ _directmap variable, modify according to USAGE above.
<From this C compiler to another C compiler>
• Compatibility can be attained using #define (refer to 11.6 Modifications of C Source for details).
• To use _ _directmap as the absolute address allocation specification, modify the program according to the
specifications of each compiler.
User’s Manual U14872EJ1V0UM
421
CHAPTER 11
EXTENDED FUNCTIONS
(32) Static model expansion specification
Static Model Expansion Specification
-ZM
FUNCTION
• The 8-byte saddr area of [email protected] to [email protected] is secured as area reserved by the compiler for
arguments and work.
• Temporary variables can be used by declaring _ _temp for arguments and automatic variables (refer to 11.5
(33) Temporary variables for details).
• The number of argument declarations that can be described ranges from 3 to 6 for int-sized variables and 3
to 9 for char-sized variables. The 4th and subsequent arguments are set by the calling side to the area of
[email protected] to [email protected] and copied by the called side to a separate area. However, if _ _temp has been
declared for a leaf function or an argument, the called side will not copy the argument, and the [email protected]
area where the argument was set will be used as is.
• Structures and unions that are 2 bytes or smaller can be described for arguments.
• Structures and unions can be described for function return values. If the structures and unions are 2 bytes or
smaller, the value will be returned. If 3 bytes or larger the return value will be stored in a static area secured
for storing return values and returned to the top address of that area.
• The 8-byte area of [email protected] to [email protected] is also used as the leaf function shared area. In shared-area
allocation, the 8-byte area of [email protected] to [email protected] is allocated to first, and then the [email protected] area
secured by specifying the -SM option.
• Arrays, unions, and structures can also be allocated to [email protected] and [email protected], provided their size fits
into the [email protected] area secured by specifying [email protected] and -SM.
• Interrupt functions that are targeted for saving are shown in Table 11-15 below.
Table 11-15. Interrupt Functions Targeted for Saving
Restore/Save Area
422
NO BANK
With Function Call
Without Function Call
-ZM1
-ZM2
-ZM1
-ZM2
Registers used
×
×
×
√
√
All registers
×
√
√
×
×
Entire [email protected] area
×
√
√
×
×
Entire [email protected] area
×
√
×
×
×
[email protected] area used
×
×
√
×
√
√:
Saved
×:
Not saved
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
Note, however, that when #pragma interrupt is specified, the interrupt functions that are targeted for saving
can be limited by specifying as follows.
SAVE_R (save/restore targets limited to registers)
SAVE_RN (save/restore targets limited to registers and [email protected]).
• The only difference between the -ZM1 and -ZM2 options is in the treatment of the [email protected] area secured
by specifying -SM.
When the -ZM1 option is specified, the [email protected] area is only used for leaf function shared area.
When the -ZM2 option is specified, the [email protected] area is saved/restored and arguments and automatic
variables are allocated there (compatibility with the -QR option in the normal model).
• If the -ZM option is specified when the -SM option has not been specified, a W055 warning message is output
and the -ZM option specification is ignored.
EFFECT
Restrictions on existing static models can be relaxed, improving descriptiveness.
USAGE
Specify the -ZM option during compilation.
EXAMPLE 1
(C source)
char funcl(char a, char b, char c, char d, char e);
char func2(char a, char b, char c, char d);
void main()
{
char a = 1, b = 2, c = 3, d = 4, e = 5, r;
r = func1(a, b, c, d, e);
}
char func1(char a, char b, char c, char d, char e)
{
char r;
r = func2(a, b, c, d);
return e + r;
}
char func2(char a, char b, char c, char d)
{
return a + b + c + d;
}
User’s Manual U14872EJ1V0UM
423
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object)
When -SM8, -ZM1, and -QC are specified
_main:
; line
5 :
char a = 1, b = 2, c = 3, d = 4, e = 5, r;
mov
a,#01H
mov
!L0003,a
inc
a
mov
!L0004,a
inc
a
mov
!L0005,a
inc
a
mov
!L0006,a
inc
a
mov
!L0007,a
; line
; 1
;
a
;
b
;
c
;
d
;
e
6 :
; line
7 :
r = func1(a, b, c, d, e);
mov
[email protected],a
; Sets the 5th argument to the saddr area for receiving
mov
a,!L0006
;
mov
[email protected],a
; Sets the 4th argument to the saddr area for receiving
mov
a,!L0005
;
c
movw
hl,ax
mov
a,!L0004
;
b
movw
bc,ax
mov
a,!L0003
;
a
call
!_func1
mov
!L0008,a
;
r
and passing arguments
d
and passing arguments
; line
8 : }
ret
; line
; line
9 : char func1(char a, char b, char c, char d, char e)
10 : {
_func1:
424
mov
!L0011,a
movw
ax,bc
mov
!L0012,a
movw
ax,hl
mov
!L0013,a
mov
a,[email protected]
; Copies to the static area
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object …continued)
mov
!L0014,a
;
mov
a,[email protected]
; Copies to the static area
mov
!L0015,a
;
; line
11 :
; line
12 :
; line
13 :
; line
char r;
r = func2(a, b, c, d);
mov
a,!L0014
; d
mov
[email protected],a
; Sets the 4th argument to the saddr area for receiving
mov
a,!L0013
and passing arguments
; c
movw
hl,ax
mov
a,!L0012
movw
bc,ax
mov
a,!L0011
call
!_func2
mov
!L0016,a
14 :
; a
; r
return e + r;
add
; line
; b
a,!L0015
; e
15 : }
ret
; line
16 : char func2(char a, char b, char c, char d)
; line
17 : {
_func2:
; line
; line
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
movw
ax,hl
mov
[email protected],a
18 :
return a + b + c + d;
mov
a,[email protected]
; a
add
a,[email protected]
; b
add
a,[email protected]
; c
add
a,[email protected]
; d
Uses [email protected] for the leaf function
19 : }
ret
User’s Manual U14872EJ1V0UM
425
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object …continued)
When -SM8, -ZM2, -QC are specified
@@CODE
CSEG
_main:
movw
ax,[email protected]
;
push
ax
; Saves the [email protected] to [email protected] areas
movw
ax,[email protected]
;
push
ax
;
movw
ax,[email protected]
;
push
ax
;
; line
5 :
char a = 1, b = 2, c = 3, d = 4, e = 5, r;
mov
[email protected],#01H
; a,1
mov
[email protected],#02H
; b,2
mov
[email protected],#03H
; c,3
mov
[email protected],#04H
; d,4
mov
[email protected],#05H
; e,5
; line
6 :
; line
7 :
Allocates variables to [email protected] to [email protected]
r = func1(a, b, c, d, e);
mov
a,[email protected]
; e
mov
[email protected],a
; Sets the 5th argument to the saddr area for receiving
mov
a,[email protected]
and passing arguments
; d
mov
[email protected],a
; Sets the 4th argument to the saddr area for receiving
mov
a,[email protected]
and passing arguments
; c
movw
hl,ax
mov
a,[email protected]
movw
bc,ax
mov
a,[email protected]
call
!_func1
mov
[email protected],a
; line
; b
; a
; r
8 : }
pop
ax
;
movw
[email protected],ax
; Restores the [email protected] to [email protected] areas
pop
ax
;
movw
[email protected],ax
;
pop
ax
;
movw
[email protected],ax
;
ret
426
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object …continued)
; line
; line
9 : char func1(char a, char b, char c, char d, char e)
10 : {
_func1:
[email protected],a
movw
ax,[email protected]
;
push
ax
; Saves the [email protected] to [email protected] areas
movw
ax,[email protected]
;
push
ax
;
movw
ax,[email protected]
;
push
ax
;
mov
a,[email protected]
; Restores register a
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
movw
ax,hl
mov
[email protected],a
mov
a,[email protected]
; Copies to [email protected]
mov
[email protected],a
;
mov
a,[email protected]
; Copies to [email protected]
mov
[email protected],a
;
; line
11 :
; line
12 :
; line
13 :
; line
; Saves register a
mov
char r;
r = func2(a, b, c, d);
mov
a,[email protected]
; d
mov
[email protected],a
; Sets the 4th argument to the saddr area for receiving
mov
a,[email protected]
and passing arguments
; c
movw
hl,ax
mov
a,[email protected]
movw
bc,ax
mov
a,[email protected]
call
!_func2
mov
[email protected],a
14 :
add
; b
; a
; r
return e + r;
a,[email protected]
; e
User’s Manual U14872EJ1V0UM
427
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object …continued)
L0004:
; line
15 : }
movw
hl,ax
; Saves register a
pop
ax
;
movw
[email protected],ax
; Restores the [email protected] to [email protected] areas
pop
ax
;
movw
[email protected],ax
;
pop
ax
;
movw
[email protected],ax
;
movw
ax,hl
; Restores register a
ret
; line
16 : char func2(char a, char b, char c, char d)
; line
17 : {
_func2:
; line
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
movw
ax,hl
mov
[email protected],a
18 :
return a + b + c + d;
mov
a,[email protected]
; a
add
a,[email protected]
; b
add
a,[email protected]
; c
add
a,[email protected]
; d
Uses [email protected] for the leaf function
L0006:
; line
19 : }
ret
428
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
EXAMPLE 2
(C source)
_ _sreg struct x {
unsigned char a;
unsigned char b:1;
unsigned char c:1;
} xx,yy;
_ _sreg struct y {
int a;
int b;
} ss, tt;
struct x func1(struct x);
struct y func2();
void main()
{
yy = func1(xx);
tt = func2();
}
struct x func1(struct x aa)
{
aa.a = 0x12;
aa.b = 0;
aa.c = 1;
return aa;
}
struct y func2()
{
return tt;
}
User’s Manual U14872EJ1V0UM
429
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
(Output object)
When -SM and -ZM are specified
@@CODE CSEG
_main:
;line
;line
;line
14: yy = func1(xx);
movw
ax,_xx
call
!_func1
movw
_yy,ax
15: tt = func2();
call
!_func2
movw
hl,ax
push
de
movw
de,#_tt
mov
c,#04H ;4
mov
a,[hl]
mov
[de],a
incw
hl
incw
de
dbnz
c,$$-4
pop
de
16: }
ret
;line
17: struct x func1(struct x aa)
;line
18: {
_func1:
movw
;line
19: aa.a = 0x12;
mov
;line
[email protected]
[email protected]
22: return aa;
movw
;line
; aa,18
21: aa.c = 1;
set1
;line
[email protected],#012H
20: aa.b = 0;
clr1
;line
[email protected],ax
ax,[email protected]
; aa Value returned because 2 bytes or smaller
23:}
ret
430
;line
24: struct y func2()
;line
25: {
User’s Manual U14872EJ1V0UM
-ZM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object …continued)
;line
;line
26: return tt;
movw
hl,#_tt
; Return value copied to secured static area because
push
de
; 3 bytes or larger
movw
de,#L0007
mov
c,#04H ;4
mov
a,[hl]
mov
[de],a
incw
hl
incw
de
dbnz
c,$$-4
pop
de
movw
ax,#L0007
; Returns top address of static area
27: }
ret
COMPATIBILITY
<From another C compiler to this C compiler>
• The source program need not be modified.
<From this C compiler to another C compiler>
• The source program need not be modified.
User’s Manual U14872EJ1V0UM
431
CHAPTER 11
EXTENDED FUNCTIONS
(33) Temporary variables
Temporary Variables
_ _temp
FUNCTION
• Arguments and automatic variables are allocated to the area of [email protected] to [email protected], regardless of
whether they correspond to a leaf function. If arguments and automatic variables are not allocated to the
area of [email protected] to [email protected] they will be treated in the same way as when _ _temp is not declared.
• The values of arguments and automatic variables declared by _ _temp are discarded upon a function call.
• _ _temp cannot be declared for external and static variables.
• If _ _sreg is declared as well, char/unsigned char/short/unsigned short/int/unsigned int variables can be
bit manipulated.
• If _ _temp is declared when the -SM and -ZM options have not been specified, a W339 warning message is
output and the _ _temp declaration in the file is disregarded.
EFFECT
• Because arguments and automatic variables declared by _ _temp share the area of [email protected] to
[email protected], an argument and automatic variable area can be reserved.
• If the sections containing arguments and those containing automatic variables are clearly identified and the
_ _temp declaration is applied to variables that do not require a guaranteed value match before and after a
function call, memory can be reserved.
USAGE
Specify the -SM and -ZM options during compilation and declare _ _temp for arguments and automatic
variables.
EXAMPLE
(C source)
void func1(_ _temp char a, char b, char c, _ _sreg _ _temp char d);
void func2(char a);
void main()
{
func1(1, 2, 3, 4);
}
void func1(_ _temp char a, char b, char c, _ _sreg _ _temp char d)
{
_ _temp char r;
d.1 = 0;
r = a + b + c + d;
func2(r);
}
void func2(char r)
{
int a = 1, b = 2;
r++;
}
432
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Temporary Variables
_ _temp
(Output object)
When -SM, -ZM, and -QC are specified
@@CODE
CSEG
_main:
; line
5 :
func1(1, 2, 3, 4);
mov
a,#04H
mov
[email protected],a
mov
h,#03H
; 3
mov
b,#02H
; 2
sub
a,#03H
; 3
call
!_func1
; line
; 4
6 : }
ret
; line
7 : void func1(_ _temp char a, char b, char c, _ _sreg _ _temp char d)
; line
8 : {
_func1:
mov
[email protected],a
movw
ax,bc
mov
!L0005,a
movw
ax,hl
mov
!L0006,a
; Allocates to [email protected]
; Argument allocated to [email protected] is unchanged
; line
9 :
; line
10 :
; line
11 :
_ _temp char r;
d.1 = 0;
clr1
; line
; line
12 :
[email protected]
r = a + b + c + d;
mov
a,[email protected]
; a
add
a,!L0005
; b
add
a,!L0006
; c
add
a,[email protected]
; d
mov
[email protected],a
; r
13 :
func2(r);
call
!_func2
; Values in [email protected] to [email protected] are changed
; after return
; line
14 : }
ret
; line
15 : void func2(char r)
; line
16 : {
User’s Manual U14872EJ1V0UM
433
CHAPTER 11
EXTENDED FUNCTIONS
Temporary Variables
_ _temp
(Output object …continued)
_func2:
mov
; line
17 :
[email protected],a
int a = 1, b = 2;
movw
ax,#01H ; 1
movw
[email protected],ax
incw
ax
movw
[email protected],ax
; line
18 :
; b
r++;
inc
; line
; a
[email protected]
19 : }
ret
RESTRICTIONS
If there are 3 arguments or fewer when a function is called, arguments and automatic variables declared by
_ _temp can be described for the arguments at function call. If there are 4 or more arguments, because the
values of the arguments could be discarded during argument evaluation, values described cannot be
guaranteed.
COMPATIBILITY
<From another C compiler to this C compiler>
• Modification is not necessary if the reserved word _ _temp is not used.
• To change to a temporary variable, modify according to USAGE above.
<From this C compiler to another C compiler>
• Compatibility can be attained using #define (refer to 11.6 Modifications of C Source for details).
This modification means that the _ _temp variable is treated as an ordinary variable.
434
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(34) Library supporting prologue/epilogue
Library Supporting Prologue/Epilogue
-ZD
FUNCTION
• A specified pattern of the prologue/epilogue code can be replaced with a library call.
• The number of callt entries that users can use is reduced by two in the case of a normal model and up to ten
in the case of a static model.
• The library replacement patterns in the case of a normal model are as follows.
HL,[email protected] save/copy, stack frame secure Æ callt [@@cprep2]
HL,[email protected] restore, stack frame release
Æ callt [@@cdisp2]
• In the case of a static model, arguments are allocated to [email protected] and [email protected] so that the first 3
arguments accord with the patterns described below. When char and int are mixed, the allocation interval is
adjusted so that it accords with the patterns of multiple int type arguments.
• The library replacement pattern in the case of a static model is as follows.
(For char 2 arguments)
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
→
callt [@@nrcp2]
→
callt [@@krcp2]
→
callt [@@nrcp3]
→
callt [@@krcp3]
→
call [email protected]@nkrc3
(For char 3 arguments)
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
movw
ax,hl
mov
[email protected],a
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
movw
ax,hl
mov
[email protected],a
mov
[email protected],a
movw
ax,bc
mov
[email protected],a
movw
ax,hl
mov
[email protected],a
User’s Manual U14872EJ1V0UM
435
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
(For int 2 arguments)
movw
[email protected],ax
movw
ax,bc
movw
[email protected],ax
movw
[email protected],ax
movw
ax,bc
movw
[email protected],ax
→
callt [@@nrip2]
→
callt [@@krip2]
→
callt [@@nrip3]
→
callt [@@krip3]
→
call [email protected]@nkri31
→
call [email protected]@nkri32
(For int 3 arguments)
436
movw
[email protected],ax
movw
ax,bc
movw
[email protected],ax
movw
ax,hl
movw
[email protected],ax
movw
[email protected],ax
movw
ax,bc
movw
[email protected],ax
movw
ax,hl
movw
[email protected],ax
movw
[email protected],ax
movw
ax,bc
movw
[email protected],ax
movw
ax,hl
movw
[email protected],ax
movw
[email protected],ax
movw
ax,bc
movw
[email protected],ax
movw
ax,hl
movw
[email protected],ax
User’s Manual U14872EJ1V0UM
-ZD
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(For save/restore)
→
callt [@@nrsave]
[email protected] to [email protected] restore →
callt [@@nrload]
[email protected] to [email protected] save
[email protected] to 15 save
→
call [email protected]@krs02
[email protected] to 15 save
→
→
call [email protected]@krs04
call [email protected]@krs04i
[email protected] to 15 save
→
→
call [email protected]@krs06
call [email protected]@krs06i
[email protected] to 15 save
→
→
call [email protected]@krs08
call [email protected]@krs08i
[email protected] to 15 save
→
→
call [email protected]@krs10
call [email protected]@krs10i
[email protected] to 15 save
→
→
call [email protected]@krs12
call [email protected]@krs12i
[email protected] to 15 save
→
→
call [email protected]@krs14
call [email protected]@krs14i
[email protected] to 15 save
→
→
call [email protected]@krs16
call [email protected]@krs16i
[email protected] to 15 restore
→
call [email protected]@krl02
[email protected] to 15 restore
→
→
call [email protected]@krl04
call [email protected]@krl04i
[email protected] to 15 restore
→
→
call [email protected]@krl06
call [email protected]@krl06i
[email protected] to 15 restore
→
→
call [email protected]@krl08
call [email protected]@krl08i
[email protected] to 15 restore
→
→
call [email protected]@krl10
call [email protected]@krl10i
[email protected] to 15 restore
→
→
call [email protected]@krl12
call [email protected]@krl12i
[email protected] to 15 restore
→
→
call [email protected]@krl14
call [email protected]@krl14i
[email protected] to 15 restore
→
→
call [email protected]@krl16
call [email protected]@krl16i
User’s Manual U14872EJ1V0UM
437
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
EFFECT
By replacing prologue and epilogue code with a library, object code can be shortened.
USAGE
Specify the -ZD option during compilation.
EXAMPLE 1
(C source)
int func1(int a, int b, int c);
int func2(int a, int b, int c);
void main()
{
int r;
r = func1(1, 2, 3);
}
int func1(int a, int b, int c)
{
return func2(a+1, b+1, c+1);
}
int func2(int a, int b, int c)
{
return a+b+c;
}
438
User’s Manual U14872EJ1V0UM
-ZD
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(Output object)
(When -SM, -ZM2D, and -QC are specified)
@@CODE CSEG
_main:
movw
ax,[email protected]
push
ax
;line
5:
;line
6:
;line
7:
int r;
r = func1(1, 2, 3);
movw
hl,#03H ; 3
movw
bc,#02H ; 2
movw
ax,#01H ; 1
call
!_func1
movw
;line
8:
[email protected],ax
;r
}
pop
ax
movw
[email protected],ax
ret
;line
9:
int func1(int a, int b, int c)
;line
10:
{
_func1:
call
[email protected]@krs06
callt
[@@krip3]
;line
11:
return func2(a+1, b+1, c+1);
movw
ax,[email protected]
incw
ax
movw
hl,ax
movw
ax,[email protected]
incw
ax
movw
bc,ax
movw
ax,[email protected]
incw
ax
call
!_func2
;c
;b
;a
L0004:
;line
12:
call
}
[email protected]@krl06
ret
;line
13:
int func2(int a, int b, int c)
;line
14:
{
_func2:
callt
[@@nrip3]
User’s Manual U14872EJ1V0UM
439
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
(Output object …continued)
;line
15:
return a+b+c;
movw
ax, [email protected]
xch
a,x
add
a, [email protected]
xch
a,x
addc
a, [email protected]
xch
a,x
add
a, [email protected]
xch
a,x
addc
a, [email protected]
;a
;b
;b
;c
;c
L0006:
;line
16:
}
ret
EXAMPLE 2
(C source)
int func(register int a, register int b);
void main()
{
register int a = 1, b = 2, c = 3,r;
r = func(a, b);
}
int func(register int a, register int b)
{
register int r;
r = a + b;
return r;
}
440
User’s Manual U14872EJ1V0UM
-ZD
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(Output object)
When -QR and -ZD are specified
@@CODE
CSEG
_main:
movw
de,#03100H
callt
[@@cprep2]
; line
4 :
register int a = 1, b = 2, c = 3, r;
movw
hl,#01H ; 1
movw
ax,hl
incw
ax
movw
[email protected],ax
incw
ax
movw
[email protected],ax ; c
; line
5 :
; line
6 :
r = func(a, b);
movw
ax,[email protected]
push
ax
movw
ax,hl
call
!_func
pop
ax
movw
ax,bc
movw
[email protected],ax
; line
7 :
; b
; b
; r
}
movw
ax,#03100H
callt
[@@cdisp2]
ret
; line
8 :
int func(register int a, register int b)
; line
9 :
{
_func:
movw
de,#0E840H
callt
[@@cprep2]
; line
10 :
; line
11 :
; line
12 :
register int r;
r = a + b;
movw
ax,hl
xch
a,x
add
a,[email protected] ; a
xch
a,x
addc
a,[email protected] ; a
movw
[email protected],ax
; r
User’s Manual U14872EJ1V0UM
441
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
(Output object …continued)
L0004:
; line
14 :
}
movw
ax,#0E840H
callt
[@@cdisp2]
ret
442
User’s Manual U14872EJ1V0UM
-ZD
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
RESTRICTIONS
• The optimization specification option -QL4 cannot be specified at the same time as the -ZD option. If it is
specified, a W052 warning message is output and the -QL4 option is replaced with the -QL3 option and
processed.
CAUTION
The argument copy pattern in the case of a static model will be pattern-matched only when register has not
been specified for any of the first 3 arguments or _ _temp has been specified for all of the first 3 arguments.
Therefore, because pattern matching will not be performed if the -QV option is specified or if register/_ _temp
are partially specified for the first 3 arguments, it will no longer be possible to replace the -ZD option
specification.
COMPATIBILITY
<From another C compiler to this C compiler>
• The source program need not be modified.
• To replace the prologue/epilogue code with a library, modify the source program according to USAGE above.
<From this C compiler to another C compiler>
• The source program need not be modified.
User’s Manual U14872EJ1V0UM
443
CHAPTER 11
EXTENDED FUNCTIONS
11.6 Modifications of C Source
By using the extended functions of this C compiler, efficient object generation can be realized. However, these
extended functions are intended for the 78K/0S Series. So, to use them for other devices, the C source may need to
be modified. Here, how to make the C source portable from another C compiler to this C compiler and vice versa is
explained.
<From another C compiler to this C compiler>
• #pragma
Note
If the other C compiler supports the #pragma preprocessing directive, the C source must be modified. The
method and extent of modifications to the C source depend on the specifications of the other C compiler.
• Extended specifications
If the other C compiler has extended specifications such as addition of keywords, the C source must be
modified. The method and extent of modifications to the C source depend on the specifications of the other C
compiler.
Note #pragma is one of the preprocessing directives supported by ANSI. The character string following
#pragma is identified as a directive to the compiler. If the compiler does not support this directive, the
#pragma directive is ignored and the compile will be continued until it properly ends.
<From this C compiler to another C compiler>
Because this C compiler has added keywords as the extended functions, the C source must be made portable to
the other C compiler by deleting such keywords or delimiting them with #ifdef.
EXAMPLE
<1> To invalidate a keyword (the same applies to callf, sreg, noauto, and norec, etc.)
#ifndef _ _K0S_ _
/* makes callt as ordinary function */
#define callt
#endif
<2> To change from one type to another
#ifndef _ _K0S_ _
#define bit char
/* changes bit type to char type variable */
#endif
444
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7 Function Call Interface
The following will be explained about the interface between functions at function call.
1. Return value (common in all the functions)
2. Ordinary function call interface
(1) Passing arguments
(2) Location and order of storing arguments
(3) Location and order of storing automatic variables
3. noauto function call interface
(1) Passing arguments
(2) Location and order of storing arguments
(3) Location and order of storing automatic variables
4. norec function call interface
(1) Passing arguments
(2) Location and order of storing arguments
(3) Location and order of storing automatic variables
5. Static model function call interface
(1) Passing arguments
(2) Location and order of storing arguments
(3) Location and order of storing automatic variables
6. Pascal function call interface
User’s Manual U14872EJ1V0UM
445
CHAPTER 11
EXTENDED FUNCTIONS
11.7.1 Return value
The function called stores the return value in the registers and carry flags as shown in Table 11-16.
Table 11-16. Location of Storing Return Value
Model
Normal Model
Static Model
Type
1-byte integer
A
BC
2-byte integer
AX
4-byte integer
BC (Lower)
DE (Upper)
Not supported
Pointer
BC
AX
Structure, union
BC (if copied to the area specific to the
function, the start address of the
structure or union)
Not supported
1 bit
CY (carry flag)
CY (carry flag)
Floating-point number (float type)
BC (Lower)
DE (Upper)
Not supported
Floating-point number (double type)
BC (Lower)
DE (Upper)
Not supported
446
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7.2 Ordinary function call interface
When all the arguments are allocated to registers and there are no automatic variables, the ordinary function call
interface is the same as noauto function call interface.
(1) Passing arguments
• There are two types of arguments: arguments that are allocated to registers and normal arguments.
• An argument that is allocated to a register is an argument that has undergone register declaration and is
allocated to a register or [email protected] as long as an allocatable register and [email protected] exist. However,
arguments are allocated to [email protected] only when -QR is specified. Arguments that are allocated to a
register or [email protected] are referred to as register arguments hereafter.
• Refer to APPENDIX A LIST OF LABELS FOR saddr AREA for [email protected]
• The remaining arguments are allocated to a stack.
• On the function call side, both the arguments declared with registers and the ordinary arguments are passed
in the same manner. The second argument and later are passed via a stack, and the first argument is passed
via a register or stack.
• On the function definition side, arguments passed via register or stack are saved in the place where
arguments are allocated.
• Register arguments are copied to a register or [email protected] Even when the arguments are passed via
registers, register copying is necessary since the registers on the function caller (passing side) are different to
those on the function definition side (receiving side).
• Normal arguments are loaded on a stack. When an argument is passed via a stack, the area where the
arguments are passed to becomes the area to which they are allocated.
• Saving and restoring registers to which arguments are allocated is performed on the function definition side.
• The location where the first argument is passed is shown in Table 11-17.
Table 11-17. Location Where First Argument Is Passed (on Function Call Side)
Option
Normal Model
Type
1-byte dataNote
2-byte dataNote
AX
3-byte dataNote
AX, BC
Note
4-byte data
AX, BC
Floating-point number (float type)
AX, BC
Floating-point number (double type)
AX, BC
Others
Passed via stack
Note
1- to 4-byte data includes structures, unions, and pointers.
User’s Manual U14872EJ1V0UM
447
CHAPTER 11
EXTENDED FUNCTIONS
(2) Location and order of storing arguments
• There are two types of arguments: arguments allocated to registers and ordinary arguments. Arguments
allocated to registers are arguments declared with registers and arguments when -QV is specified.
• The arguments not allocated to registers are allocated to stacks. The arguments allocated to stacks are
placed on the stack sequentially from the last argument.
• Saving and restoring registers to which arguments are allocated is performed on the function definition side.
• On the function definition side, the arguments that are passed via a register or stack are stored in the area to
which arguments are allocated.
• The register arguments are copied to a register or [email protected] Copying to [email protected] is performed only
when -QR is specified. Even when the arguments are passed via registers, register copying is necessary
since the registers on the function caller (passing side) are different to those on the function definition side
(receiving side).
• On the function caller side, both register arguments and normal arguments are passed using the same
method.
The second or later arguments are passed via a stack. The first argument is passed via a register or stack.
Refer to Table 11-17 for the place where the first argument is passed.
(Registers to be used)
HL
Arguments are not allocated to HL when there is a stack frame.
(saddr area to be used)
[email protected] to 15
(Allocation sequence)
• Registers
char type:
The sequence is L-H.
int, short, and enum type: HL
• saddr area
char type:
The sequence is [email protected], [email protected], [email protected], and [email protected]
int, short, and enum type: The sequence is [email protected] to 13 and [email protected] to 15.
long, float, double type:
448
The sequence is [email protected] to 13 (lower)[email protected] to 15 (higher).
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables
• There are two types of automatic variables: automatic variables to be allocated to registers and ordinary
automatic variables. The automatic variables to be allocated to registers are ones which are declared with
registers and automatic variables with -QV is specified. They are allocated to registers and [email protected] as
long as there are allocable registers and [email protected]
However, automatic variables are allocated to
[email protected] only when -QR is specified.
The automatic variables allocated to registers and [email protected] are called register variables hereafter.
• For [email protected], refer to APPENDIX A LIST OF LABELS FOR saddr AREA.
• Register variables are allocated after register arguments are allocated. Therefore, register variables are
allocated to registers when there are excess registers after the allocation of register arguments.
• The automatic variables not allocated to a register are allocated to a stack.
• Saving and restoring registers and [email protected] to which automatic variables are allocated is performed on
the function definition side.
(a) Automatic variable allocation sequence
The sequence of allocating automatic variables to [email protected] is as follows.
(Registers to be used)
HL
Arguments are not allocated to HL when there is a stack frame.
(saddr area to be used)
[email protected] to 15
(Allocation sequence)
• Registers
char type:
The sequence is L and H.
int, short, and enum type: HL
• saddr area
char type:
The sequence is [email protected], [email protected] ..., and [email protected]
int, short, and enum type: The sequence is [email protected] to 01, [email protected] to 03 ... and [email protected]
to 15.
long, float, double type:
The sequence is [email protected] to 03, [email protected] to 07, and [email protected] to
15.
• The automatic variables that are allocated to a stack are loaded on the stack in the sequence of
declaration.
User’s Manual U14872EJ1V0UM
449
CHAPTER 11
EXTENDED FUNCTIONS
[Example]
In the normal model
(C source 1)
void func0 (register int, int) ;
void main ()
{
func (0x1234, 0x5678) ;
}
void func (register int p1, int p2)
{
register int r ;
int a ;
r = p2 ;
a = p1 ;
}
(Output code)
_main:
; line
4: func0 (0x1234, 0x5678) ;
movw
ax, #05678H
; 22136
; Receives/passes an argument via a stack
push
ax
movw
ax, #01234H
call
!_func0
; Function call
pop
ax
; Receives/passes an argument via a stack
; line
; 4660
; Passes the 1st argument to a register
5: }
ret
; line
6: void func0 (register int p1, int p2)
; line
7: {
_func0:
450
push
hl
xch
a, x
xch
a, [email protected]
xch
a, x
xch
a, [email protected]
; Allocates register argument p1 to [email protected]
push
ax
; Saves the saddr area for register arguments
movw
ax, [email protected]
push
ax
; Saves the saddr area for register variables
push
ax
; Reserves the area for automatic variable a
movw
ax, sp
movw
hl, ax
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) (continued)
; line
8: register int r ;
; line
9: int a ;
; line
10: r = p2 ;
; p2
; Assigns argument p2, which is received/passed via
mov
a, [hl + 10]
xch
a, x
mov
a, [hl + 11]
; p2
movw
[email protected], ax
; r
; to register variable [email protected]
; Assigns register argument [email protected] to
; a stack,
; line
11: a = p1 ;
movw
ax, [email protected]
; p1
mov
[hl + 1], a
; a
xch
a, x
mov
; line
[hl], a
; a
; Automatic variable a
12: }
pop
ax
pop
ax
movw
[email protected], ax
pop
ax
movw
[email protected], ax
pop
hl
; Releases the area for automatic variable a
; Restores the saddr area for register variables
; Restores the saddr area for register arguments
ret
User’s Manual U14872EJ1V0UM
451
CHAPTER 11
EXTENDED FUNCTIONS
(C source 2)
void func1 (int, register int) ;
void main ()
{
func1 (0x1234, 0x5678) ;
}
void func1 (int p1, register int p2)
{
register int r ;
int a ;
r = p2 ;
a = p1 ;
}
(Output code)
_main:
; line
movw
4: func1 (0x1234, 0x5678) ;
ax, #05678H
; 22136
; Receives/passes an argument via a stack
push
ax
movw
ax, #01234H
call
!_func1
; Function call
pop
ax
; Receives/passes an argument via a stack
; line
; 4660
; Passes the 1st argument to a register
5: }
ret
; line
6: void func1 (int p1, register int p2)
; line
7: {
_func1:
push
hl
; Loads 1st argument p1 on the stack
push
ax
movw
ax, [email protected]
push
ax
movw
ax, [email protected]
push
ax
; Saves the saddr area for register arguments
push
ax
; Reserves the area for automatic variable a
movw
ax, sp
movw
hl, ax
mov
a, [hl + 12]
; Saves the saddr area for register arguments
; Passes argument p2 from the stack to the saddr
area
xch
a, x
mov
a, [hl + 13]
movw
452
; Allocates the register argument to [email protected]
[email protected], ax
; line
8: register int r ;
; line
9: int a ;
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) (continued)
; line
movw
movw
; line
mov
10: r = p2 ;
ax, [email protected]
; p2
[email protected], ax
; r
; Register variable [email protected]
11: a = p1 ;
a, [hl + 6]
; p1
; Passes argument p1 (lower) from register
; a
; to stack
; Automatic variable a (lower)
mov
[hl] , a
xch
a, x
mov
a, [hl + 7]
; p1
; Passes argument p1 (higher) from register
mov
[hl + 1] , a
; a
; to stack
; Automatic variable a (higher)
; line
12: }
pop
ax
pop
ax
movw
[email protected], ax
pop
ax
movw
[email protected], ax
pop
ax
pop
hl
; Releases area of automatic variable a
; Restores the saddr area for register variables
; Restores the saddr area for register arguments
ret
User’s Manual U14872EJ1V0UM
453
CHAPTER 11
EXTENDED FUNCTIONS
11.7.3 noauto function call interface (normal model only)
(1) Passing arguments
• On the function caller, arguments are passed in the same way as ordinary functions.
Refer to 11.7.2
Ordinary function call interface.
• On the function definition side, arguments passed via a register or stack are copied to a register as well as
[email protected] to 15. Copying to [email protected] to 15 is performed only when -QR is specified. Even when the
arguments are passed via registers, register copying is necessary since the registers on the function caller
(passing side) are different to those on the function definition side (receiving side).
• Saving and restoring registers to which arguments are allocated is performed on the function definition side.
(2) Location and order of storing arguments
• On the function definition side, all arguments are allocated to registers and [email protected] to 15. However,
arguments are allocated to [email protected] to 15 only when -QR is specified.
• If there are arguments that are not allocated to registers or [email protected] to 15 an error will result.
• On the function caller, arguments are passed in the same way as in an ordinary function (Refer to 11.7.2
Ordinary function call interface).
• On the function definition side, the arguments passed via a register or stack are copied to a register as well as
[email protected] to 15. Even when the arguments are passed via registers, register copying is necessary since
the registers on the function caller (passing side) are different to those on the function definition side
(receiving side).
• Saving and restoring registers to which arguments are allocated is performed on the function definition side.
(Allocation sequence)
• The allocation sequence is the same as for ordinary functions (refer to 11.7.2 Ordinary function call
interface).
454
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables
Automatic variables are allocated to registers and [email protected] to 15.
However, automatic variables are
allocated to [email protected] to 15 only when -QR is specified. For [email protected] to 15, refer to APPENDIX A LIST
OF LABELS FOR saddr AREA.
Automatic variables are allocated to registers when there are excess registers after the allocation of arguments.
When -QR is specified, automatic variables are also allocated to [email protected] to 15.
If an automatic variable cannot be allocated to a register or [email protected] to 15, an error occurs.
Saving and restoring the registers and [email protected] to 15 to which automatic variables are allocated is performed
on the function definition side.
(Allocation sequence)
• The order of allocating automatic variables to registers is the same as the order of allocating arguments.
• The automatic variables allocated to [email protected] to 15 are allocated in the order of declaration.
[Example]
(C source)
noauto void func2 (int, int) ;
void main ()
{
func2 (0x1234, 0x5678) ;
}
noauto void func2 (int p1, int p2)
{
.
.
.
}
User’s Manual U14872EJ1V0UM
455
CHAPTER 11
EXTENDED FUNCTIONS
(Output code)
_main:
; line
4: func2 (0x1234, 0x5678) ;
movw
ax, #05678H
push
ax
movw
ax, #01234H
call
!_func2
; Function call
ax
; Argument passed via a stack
pop
; line
; 22136
; Argument passed via a stack
; 4660
; The first argument that is passed via a register
5: }
ret
; line
6: noauto void func2 (int p1, int p2)
; line
7: {
_func2:
push
hl
xch
a, x
; Saves a register for arguments
; Allocates argument p1 to [email protected] (lower)
xch
a, [email protected]
xch
a, x
xch
a, [email protected]
; Allocates argument p1 to [email protected] (higher)
push
ax
; Saves the saddr area for arguments
movw
ax, sp
movw
hl, ax
mov
a, [hl + 6]
; Argument p2 (lower) passed via a stack
and received via a register
xch
a, x
mov
a, [hl + 7]
; Argument p2 (higher) passed via a stack
movw
hl, ax
and received via a register
; Allocates arguments to HL
.
.
.
pop
ax
movw
[email protected], ax
; Restores the saddr area for arguments
pop
hl
; Restores the register for arguments
ret
456
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7.4 norec function call interface (normal model)
(1) Passing arguments
All arguments are allocated to [email protected] and [email protected] and 7. On the function caller side, arguments are
passed via register [email protected]
On the function definition side, arguments passed via registers are copied to registers, or to [email protected] and 7
(Refer to APPENDIX A LIST OF LABELS FOR saddr AREA).
(2) Location and order of storing arguments
• On the function definition side, all arguments are allocated to registers, [email protected], [email protected] and 7.
Arguments are allocated to [email protected] only when -QR is specified.
• Arguments are allocated to [email protected] and 7 only when there are arguments in DE (Refer to APPENDIX A
LIST OF LABELS FOR saddr AREA).
• If there are arguments that are not allocated to registers, [email protected], [email protected] and 7, an error will result.
• On the function caller side, arguments are passed via registers and [email protected]
• On the function definition side, arguments that are passed via registers are copied to registers or [email protected]
and 7. Even when the arguments are passed via registers, register copying is necessary since the registers
on the function caller side (passing side) are different to those in the function definition side (receiving side).
If the arguments are passed via registers, the area where the arguments are passed becomes the area to
which they are allocated.
• If arguments can no longer be passed via a register, they can be allocated to [email protected] and passed via
there. In this case, passing is carried out with registers and [email protected] intermingled.
(Argument allocation sequence)
• Arguments allocated to [email protected] are allocated in the sequence of declaration.
• Arguments allocated to registers are allocated to registers, [email protected] and 7 according to the following
rules.
(Registers to be used)
• When one argument is used in char, int, short, enum, or pointer type:
AX pass, DE receive
• When two or more arguments are used in char, int, short, enum, or pointer type: AX and DE pass
[email protected], 7
DE receive
(Allocation sequence)
• char, int, short, enum, and pointer type:
In the sequence of DE,
[email protected] and 7
User’s Manual U14872EJ1V0UM
457
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables
Automatic variables are allocated to registers and [email protected] as long as there are allocable registers and
[email protected] If there is no allocable register, they are allocated to [email protected]
However, automatic variables are allocated to [email protected] and [email protected] only when -QR is specified.
For [email protected], refer to APPENDIX A LIST OF LABELS FOR saddr AREA.
If there is an automatic variable that cannot be allocated to a register, [email protected] and [email protected], an error
occurs.
Saving and restoring registers to which automatic variables are allocated is performed on the function definition
side.
(Allocation sequence)
• The order of allocating automatic variables to registers, [email protected] to 7 is the same as the order of
allocating arguments.
• The automatic variables allocated to [email protected], [email protected] are allocated in the order of declaration.
[Example]
In the normal model
(C source)
norec void func3 (char, int, char, int) ;
void main ()
{
func3 (0x12, 0x34, 0x56, 0x78) ;
}
norec void func3 (char p1, int p2, char p3, int p4)
{
int a ;
a = p2 ;
}
458
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(Output code)
When -QR is specified
_main :
; line
4 : func3 (0x12, 0x34, 0x56, 0x78) ;
; Argument is passed via [email protected]
movw
ax, #078H
movw
[email protected], ax
mov
[email protected], #056H
; 86
; Argument is passed via [email protected]
movw
de, #034H
; 52
; Argument is passed via register DE
mov
a, #012H
; 18
; Argument is passed via register A
call
!_func3
; Function call
ret
; line
6 : norec void func3 (char p1, int p2, char p3, int p4)
; line
7 : {
_func3 :
mov
; Allocates the argument p1 to [email protected]
[email protected], a
; line
8 : int a ;
; line
9 : a = p2 ;
movw
ax, de
movw
[email protected], ax
; Argument p2
; a
; Automatic variable a
ret
User’s Manual U14872EJ1V0UM
459
CHAPTER 11
EXTENDED FUNCTIONS
11.7.5 Static model function call interface
(1) Passing arguments
• On the function caller side, both the register arguments and the normal arguments are passed in the same
way.
There can be a maximum of three arguments, up to 6 bytes, and all arguments are passed via registers.
• On the function definition side, the arguments passed via a register are stored in the area to which they are
allocated. Register arguments are copied to registers. Even when the arguments are passed via registers,
register copying is necessary since the registers on the function caller side (passing side) are different to
those on the function definition side (receiving side).
• Ordinary functions are allocated to the function-specific area.
(2) Location and order of storing arguments
(a) Argument storage location
• There are two types of arguments: arguments to be allocated to registers and normal arguments.
• The arguments allocated to registers are arguments that have undergone a register declaration.
• On the function definition side, the arguments that are passed via a register or stack are stored in the
area to which arguments are allocated.
Register arguments are copied to a register. Even when the arguments are passed via registers, register
copying is necessary since the registers on the function caller side (passing side) are different to those
on the function definition side (receiving side). Normal arguments are allocated to the function-specific
area.
• Saving and restoring registers to which arguments/automatic variables are allocated is performed on the
function definition side.
• The remaining arguments are allocated to the function-specific area.
• On the function caller side, both register arguments and normal arguments are passed in the same way.
There can be a maximum of three arguments, up to 6 bytes, and all arguments are passed via a register.
Table 11-18 shows the area to which arguments are passed.
Table 11-18. Areas to Which Arguments Are Passed in Static Model
Data Size
First Argument
Second Argument
Third Argument
A
B
H
AX
BC
HL
1-byte dataNote
2-byte dataNote
4-byte dataNote
Allocated to AX and BC and the remainder allocated to H or HL.
Note Neither structures nor unions are included in 1- to 4- byte data.
(b) Argument allocation sequence
• Arguments allocated to the function-specific area are allocated sequentially from the last argument.
• Register arguments are allocated to register DE according to the following rules.
(Registers to be used)
DE
(Allocation sequence)
char type:
sequence of D, E
int, short, enum type: DE
460
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables
(a) Storage location of automatic variables
• There are two types of automatic variables: automatic variables to be allocated to registers and normal
automatic variables.
• Automatic variables allocated to registers are automatic variables declared with registers and automatic
variables when -QV is specified.
• Register variables are allocated after register arguments are allocated. For this reason, the allocation of
register variables to registers is performed only when registers are superfluous after register argument
allocation.
• The remaining automatic variables are allocated to the function-specific area.
• Saving and restoring registers to which arguments are allocated is performed on the function definition
side.
(b) Automatic variable allocation sequence
• Automatic variables are allocated to register DE according to the following rules.
(Registers to be used)
DE
(Allocation sequence)
char type:
Sequence of E, D
int, short, enum type: DE
• The automatic variables that are allocated to the function-specific area are allocated in the sequence of
declaration.
[EXAMPLE 1]
(C source)
void func4 (register int, char) ;
void main ()
{
func4 (0x1234, 0x56) ;
}
void func4 (register int p1, char p2)
{
register char r ;
int a ;
r = p2 ;
a = p1 ;
}
User’s Manual U14872EJ1V0UM
461
CHAPTER 11
EXTENDED FUNCTIONS
(Output code)
@@DATA
DSEG
L0005 :
DS
; Argument p2
(1)
L0006 :
DS
(1)
; Automatic variable r
L0007 :
DS
(2)
; Automatic variable a
; line
1 : void func4 (register int, char) ;
; line
2 : void main ()
; line
3 : {
@@CODE
CSEG
_main :
; line
4 : func4 (0x1234, 0x56) ;
mov
b, #056H
; 86
; Passes the second argument via register B
movw
ax, #01234H
; 4660
; Passes the first argument via register AX
call
!_func4
; line
; Function call
5 : }
ret
; line
6 : void func4 (register int p1, char p2)
; line
7 : {
_func4 :
push
de
; Saves register for register argument
movw
de, ax
; Allocates register argument p1 to DE
movw
ax, bc
mov
8 : register char r ;
; line
9 : int a ;
; line
10 : r = p2 ;
mov
; line
; Copy argument p2 to L0005
!L0005, a
; line
!L0006, a
;r
movw
ax, de
movw
hl, #L0007
callt
[@@hlist]
; line
pop
; Register argument p1
;a
; Automatic variable a
12 : }
de
; Restores the register for register argument
ret
462
; Automatic variable r
11 : a = p1 ;
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
[EXAMPLE 2]
(C source)
void func5 (int, register char) ; void func();
void main ()
{
func5 (0x1234, 0x56) ;
}
void func5 (int p1, register char p2)
{
register char r ;
int a ;
r = p2 ;
a = p1 ; func();
}
(Output code)
@@DATA
DSEG
L0005 :
DS
(2)
L0006 :
DS
(2)
; line
1 : void func5 (int, register char) ; void func();
; line
2 : void main ()
; line
3 : {
@@CODE
CSEG
_main :
; line
; line
4 : func5 (0x1234, 0x56) ;
; Passes the second argument via register B
mov
b, #056H
; 86
movw
ax, #01234H
; 4660 ; Passes the first argument via register AX
call
!_func5
; Function call
5 : }
ret
; line
6 : void func5 (int p1, register char p2)
; line
7 : {
_func5 :
push
de
; Saves a register for register variables and
movw
hl, #L0005
; Copies argument p1 to L0005
callt
[@@hlist]
movw
ax, bc
; register arguments.
User’s Manual U14872EJ1V0UM
463
CHAPTER 11
EXTENDED FUNCTIONS
(Output code …continued)
mov
; line
; line
9 : int a ;
; line
10 : r = p2 ;
; line
; line
; Allocates a register argument p2 to d.
de, ax
8 : register char r ;
movw
ax, de
; Register argument p2
mov
e, a
; Register variable r
11 : a = p1 ; func();
movw
hl, #L0005
callt
[@@hlilo]
movw
hl, #L0006
callt
[@@hlist]
call
!_func
; p1
; Argument p1
; a
; Automatic variable a
12 : }
pop
de
; Restores the register for register arguments
ret
464
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7.6 Pascal function call interface
The difference between this function interface and other function interfaces is that the correction of stacks used for
loading of arguments when a function is called is done on the function side that was called, rather than the function
caller side. All other points are the same as the function attributes specified at the same time.
[Area to which arguments are allocated]
[Sequence in which arguments are allocated]
[Area to which automatic variables are allocated]
[Sequence in which automatic variables are allocated]
• If the noauto attribute is specified at the same time, the features are the same as when a noauto function is
called (refer to 11.7.3 noauto function call interface).
• If the noauto attribute is not specified at the same time, the features are the same when an ordinary function is
called (refer to 11.7.2 Ordinary function call interface).
EXAMPLE 1
(C source)
_ _pascal void func0 (register int, int) ;
void main ()
{
func0 (0x1234, 0x5678) ;
}
_ _pascal void func0 (register int p1, int p2)
{
register int r ;
int a ;
r = p2 ;
a = p1 ;
}
User’s Manual U14872EJ1V0UM
465
CHAPTER 11
EXTENDED FUNCTIONS
(Output code)
When -QR option is specified
_main:
; line
4
:func0 (0x1234, 0x5678) ;
movw
ax, #05678H
push
ax
movw
ax, #01234H
call
!_func0
; line
5:
; 22136
; 4660
; Stack is passed via the argument
; The first argument that is passed via a register
; Function call
; Stack is not corrected here
}
ret
; line
6
:_ _pascal void func0 (register int p1, int p2)
; line
7
:{
_func0:
push
hl
xch
a, x
xch
a,[email protected]
xch
a, x
xch
a,[email protected]
push
ax
movw
ax,[email protected]
push
ax
push
ax
movw
ax, sp
movw
hl, ax
; Allocates register argument p1 to [email protected]
; Saves the saddr area for register arguments
; Saves the saddr area for register variables
; Reserves the automatic variable a area
; line
8
:register int r ;
; line
9
:int a;
; line
10
:r = p2;
a, [hl + 10]
xch
a, x
mov
a, [hl + 11]
; p2
movw
[email protected], ax
; r
; Assigned to register variable [email protected]
; Register argument [email protected]
; line
; p2
; Stack transfer argument p2
mov
11 :a = p1 ;
movw
ax,[email protected]
; p1
mov
[hl + 1], a
; a
xch
a, x
mov
; line
[hl], a
; a
; Assigned to automatic variable a
12 :}
; Releases the automatic variable a area
pop
ax
pop
ax
movw
[email protected], ax
pop
ax
movw
[email protected], ax
pop
hl
pop
de
; Obtains the return address
pop
ax
; Corrects the stack consumed by arguments passed via a stack
push
de
; Reloads the return address
; Restores the saddr area for register variables
; Restores the saddr area for register arguments
ret
466
User’s Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
EXAMPLE 2
(C source)
_ _pascal noauto void func2 (int, int) ;
void main ()
{
func2 (0x1234, 0x5678) ;
}
_ _pascal noauto void func2 (int p1, int p2)
{
.
.
.
}
(Output code)
When -QR option is specified
_main:
; line
4 : func2 (0x1234, 0x5678) ;
movw
ax, #05678H ; 22136
push
ax
; Argument passed via a stack
movw
ax, #01234H ; 4660
; The first argument that is passed via a register
call
!_func2
; Function call
; The stack is not corrected here
; line
5 : }
; line
6 : _ _pascal noauto void func2 (int p1, int p2)
; line
7 : {
ret
_func2:
; Saves the register for arguments
push
hl
xch
a, x
xch
a,[email protected]
xch
a, x
xch
a,[email protected]
; Allocates argument p1 to [email protected] (higher)
push
ax
; Saves the saddr area for arguments
movw
ax, sp
movw
hl, ax
mov
a, [hl + 6]
; Allocates argument p1 to [email protected] (lower)
; Argument p2 (lower) passed via a stack
; and received by a register
xch
a, x
User’s Manual U14872EJ1V0UM
467
CHAPTER 11
EXTENDED FUNCTIONS
(Output code … continued)
mov
a, [hl + 7]
; Argument p2 (higher) passed via a stack
; and received by a register
movw
hl, ax
; Allocates arguments to HL
.
.
.
pop
ax
movw
[email protected], ax
; Restores the saddr area for arguments
pop
hl
; Restores the register for arguments
pop
de
; Obtains the return address
pop
ax
; Corrects the stack consumed by arguments passed via a stack
push
de
; Reloads the return address
ret
468
User’s Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
This chapter describes how to link a program written in assembly language.
If a function called from a C source program is written in another language, both object modules are linked by the
linker. This chapter describes the procedure for calling a program written in another language from a program written
in the C language and the procedure for calling a program written in the C language from a program written in
another language.
How to interface with another language by using the RA78K0S Assembler Package and this C compiler is
described in this order:
(1) Calling assembly language routines from the C language
(2) Calling C language functions from assembly language
(3) Referencing variables defined in the C language
(4) Referencing variables defined in assembly language on the C language side
(5) Cautions
User’s Manual U14872EJ1V0UM
469
CHAPTER 12
REFERENCING THE ASSEMBLER
12.1 Accessing Arguments/Automatic Variables
The procedure to access arguments and automatic variables of this C compiler is described below.
12.1.1 Normal model
•
On the function call side, register arguments are passed in the same way as regular arguments.
The first argument uses the following registers and stacks, and subsequent arguments are passed via
stacks.
Table 12-1. Passing Arguments (Function Call Side)
Type
Passing Location (First Argument)
Passing Location (Second and Later Arguments)
1-byte, 2-byte data
AX
Stack passing
3-byte, 4-byte data
AX, BC
Stack passing
Floating-point number
AX, BC
Stack passing
Others
Stack passing
Stack passing
Remark 1- to 4-byte data includes structures and unions.
•
On the function definition side, arguments passed via a register or stack are stored in the argument allocation
location.
Register arguments are copied to a register or saddr area ([email protected]). Even when passing is done via a
register, the registers on the function call side (passing side) and the function definition side (receiving side)
differ, and therefore register copying is performed.
Normal arguments passed via a register are pushed to a stack on the function definition side. If passing is
done via a stack, the passing location simply becomes the argument allocation location.
Saving and restoring registers to which arguments are allocated is performed on the function definition side.
•
The arguments of functions and the values of automatic variables declared inside functions are stored in the
following registers, saddr areas, or stack frames using an option. The base pointer used when storing in a
stack frame uses the HL register.
If the function argument is register-declared or specified by the -QV option and specified by the -QR option, it
is allocated to the saddr area.
470
User’s Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
Table 12-2. Storing of Arguments/Automatic Variables (Inside Called Function)
Option
-QV
Argument/auto Variable
Storage Location
Declared argument or
automatic variable
HL register
(register allocation option)
-QR
(saddr allocation option)
register declared argument
or automatic variable
HL register
(only when base pointer is not
required)
(only when base pointer is not
required)
Argument:
[email protected] to 15
[0FEE4H to 0FEE7H]
Priority Level
char type: L, H, in this order
int, short, enum type: HL
Only the number of bytes of
the variable or argument is
allocated based on the
referenced count.
Allocated to register as
char type: L, H, in this order
int, short, enum type: HL
Automatic variable:
[email protected] to 11
[0FED8H to 0FEE3H]
[email protected] to 15 (not allocated to
arguments)
-QRV
Declared argument or
automatic variable
HL register
(only when base pointer is not
required)
Argument:
[email protected] to 15
[0FEE4H to 0FEE7H]
Only the number of bytes of
the variable or argument is
allocated based on the
referenced count.
Allocated to register as
char type: L, H, in this order
int, short, enum type: HL
Automatic variable:
[email protected] to 11
[0FED8H to 0FEE3H]
[email protected] to 15 (not allocated to
arguments)
Default
Declared argument,
automatic variable
Stack frame
Order of appearance
The following example shows the function call.
(C source: Normal model at the -QRV specification)
void func0 (register int, int);
void main(){
func0 (0x1234, 0x5678);
}
void func0 (register int p1, int p2){
register int r;
int a;
r=p2;
a=p1;
}
User’s Manual U14872EJ1V0UM
471
CHAPTER 12
REFERENCING THE ASSEMBLER
(Output assembler source)
EXTRN
EXTRN
EXTRN
EXTRN
PUBLIC
PUBLIC
@@CODE
_main:
movw
push
movw
call
pop
ret
_func0:
push
xch
xch
xch
xch
push
movw
push
movw
push
movw
movw
mov
xch
mov
movw
movw
movw
movw
movw
pop
movw
pop
movw
pop
movw
pop
ret
END
472
[email protected]
[email protected]
[email protected]
[email protected]
_func0
_main
CSEG
ax,#05678H
ax
ax,#01234H
!_func0
ax
hl
a,x
a,[email protected]
a,x
a,[email protected]
ax
ax,[email protected]
ax
ax,[email protected]
ax
ax,sp
hl,ax
a,[hl+10]
a,x
a,[hl+11]
hl,ax
ax,hl
[email protected],ax
ax,[email protected]
[email protected],ax
ax
[email protected],ax
ax
[email protected],ax
ax
[email protected],ax
hl
;22136
;4660
; Argument passed on stack
; 1st argument passed on register
; Function call
; Argument passed on stack
; Saves the register for arguments
; Allocates register argument p1 to [email protected]
; Saves the saddr area for register arguments.
; Saves the saddr area for register variables.
; Saves the saddr area for automatic variables.
; Argument p2 passed on stack
;r
;p1
;a
; Assigned to HL
; Argument p2
; Assigned to register variables r.
; Register argument p1
; Assigned to automatic variable a.
; Restores the saddr area for register variables.
; Restores the saddr area for automatic variables.
; Restores the saddr area for register arguments.
; Restores the register for arguments
User’s Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
12.1.2 Static model
•
On the function call side, register arguments are passed in the same way as regular arguments.
•
Up to 3 arguments, or a total of 6 bytes, can be passed, all via a register.
Table 12-3. Passing Arguments (Function Call Side)
Type
Passing Location (First Argument)
Passing Location (Second Argument)
Passing Location (Third Argument)
1-byte data
A
B
H
2-byte data
AX
BC
HL
4-byte data
Allocated to AX and BC, remainder allocated to H or HL
Remark 1- to 4-byte data does not include structures and unions.
•
On the function definition side, arguments passed via a register are stored to the argument allocation
location.
Arguments (register arguments) declared with register are allocated to registers whenever possible, and
regular arguments are allocated to areas reserved for specific functions.
•
All register arguments are passed via registers, but the registers on the function call side (passing side) and
•
Saving and restoring of registers to which arguments/automatic variables are allocated is performed on the
•
Function arguments and the values of automatic variables declared inside functions are stored in the
the function definition side (receiving side) differ, and therefore register copying is performed.
function definition side.
function-specific areas listed below using an option.
Function-specific areas are static areas in RAM
reserved for each function.
Table 12-4. Storing of Arguments/Automatic Variables (Inside Called Function)
Option
-QV
(register allocation option)
Argument/auto Variable
Declared argument or
automatic variable
Storage Location
DE register
Priority Level
Arguments:
char type: D, E, in this order
int, short, enum type: DE
Automatic variables:
char type: E, D, in this order
int, short, enum type: DE
Default
Declared argument,
automatic variable
Function-specific area
Arguments are allocated starting from
the 1st argument, automatic variables
are allocated by order of appearance
Default
Argument, register variable
declared with register
DE register
Only the number of bytes of the
variable or argument is allocated,
according to the number of times
referenced.
Other than the number of bytes of the
variable or argument is allocated to the
area peculiar to the function.
User’s Manual U14872EJ1V0UM
473
CHAPTER 12
REFERENCING THE ASSEMBLER
The following example shows the function call.
(C source: Static Model at -SM and -QV specifications)
void sub();
void func (register int, char);
void main(){
func (0x1234, 0x56);
}
void func (register int p1, char p2){
register char r;
int a;
r=p2;
a=p1;
}
sub();
(Output assembler source)
_func
_main
...
PUBLIC
PUBLIC
DSEG
DS
(1)
DS
(1)
DS
(2)
; Argument p2
; Register variable r
; Automatic variable a
...
@@DATA
?L0005:
?L0006:
?L0007:
@@CODE
_main:
mov
movw
call
ret
func:
push
movw
movw
mov
mov
movw
mov
xch
mov
call
pop
ret
END
474
CSEG
b,#056H
ax,#01234H
!_func
de
de,ax
ax,bc
!?L0005,a
!?L0006,a
ax,de
!?L0007+1,a
a,x
!?L0007,a
!_sub
de
;86
;4660
; Passes the 2nd argument by register B.
; Passes the 1st argument by register AX.
; Function call
; Saves registers for register arguments.
; Allocates register arguments p1 to DE.
;r
; Copies argument p2 to ?L0005.
; Assigned to register variable r
; Register argument p1
;a
;a
; Assigned to automatic variable a
; Restores the register for register arguments.
User’s Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
12.2 Storing Return Values
Return values during function calls are stored to registers and carry flags.
The storage locations of return values are shown in the table below.
Table 12-5. Storage Location of Return Values
Type
1-byte integer
Normal Model
Static Model
A
BC
2-byte integer
AX
4-byte integer
BC (lower), DE (higher)
Not supported
Pointer
BC
AX
Structure, union
BC (start address of structure or union copied
to function-specific area)
Not supported
1 bit
CY (carry flag)
CY (carry flag)
Floating-point number
BC (low-order), DE (high-order)
Not supported
User’s Manual U14872EJ1V0UM
475
CHAPTER 12
REFERENCING THE ASSEMBLER
12.3 Calling Assembly Language Routines from C Language
This section shows examples when the normal model (default) is used. If the -QV option, -QR option, and -QRV
option are specified, arguments are stored as indicated in Table 12-2. However, the HL register is allocated only
when no base pointer is required (when base pointer is not used).
Calling an assembly language routine from the C language is described as follows.
•
C language function calling procedure
•
Saving data from the assembly language routine and returning
(1) C language function calling procedure
This is a C language program example that calls an assembly language routine.
/* Function prototype */
extern int FUNC(int, long);
void main()
{
int
long
i, j;
l;
i = 1;
l = 0x54321;
j = FUNC(i, l);
/* Function call */
}
In this program example, the interface and control flow with the program that is being executed are as follows.
(1) Placing the first argument passed from the main function to the FUNC function in the register, and the
second and subsequent arguments on the stack.
(2) Passing control to the FUNC function by using the CALL instruction.
The next figure shows the stack immediately after control moves to the FUNC function in the above program
example.
Figure 12-1. Stack Area After a Call
low address
Stack pointer
Return address to main
l (lower word)
l (higher word)
high address
Stack area
476
User’s Manual U14872EJ1V0UM
Arguments passed to
the FUNC function
AX register
i
CHAPTER 12
REFERENCING THE ASSEMBLER
(2) Saving data from the assembly language routine and returning
The following processing is performed in the FUNC function called from the main function.
(1) Save the base pointer, work register.
(2) Copy the stack pointer (SP) to the base pointer (HL).
(3) Perform the processing in the FUNC function.
(4) Set the return value.
(5) Restore the saved register.
(6) Return to the main function.
Next, an example of an assembly language program is explained.
$PROCESSOR(9024)
PUBLIC _FUNC
PUBLIC _DT1
PUBLIC _DT2
@@DATA
DSEG
?DT1:
DS
(2)
?DT2:
DS
(4)
@@CODE
CSEG
_FUNC:
; Saves base pointer --------------------------------- (1)
PUSH
HL
PUSH
AX
MOVW
AX,SP
MOVW
HL,AX
MOV
A,[HL]
; arg1
MOV
!_DT1,A
; move 1st argument(i)
XCH
A,X
MOV
A,[HL+1]
MOV
!_DT1+1,A
MOV
A,[HL+8]
XCH
A,X
MOV
A,[HL+9]
MOVW
BC,AX
MOV
A,[HL+6]
XCH
A,X
MOV
A,[HL+7]
MOVW
DE,#_DT2
; Copies stack pointer ------------------------------- (2)
; arg1
; arg2
; arg2
; arg2
; arg2
User’s Manual U14872EJ1V0UM
477
CHAPTER 12
XCH
A,X
MOV
[DE],A
XCH
A,X
INCW
DE
MOV
[DE],A
XCHW
AX,BC
INCW
DE
XCH
A,X
MOV
[DE],A
XCH
A,X
INCW
DE
MOV
[DE],A
XCHW
AX,BC
MOVW
BC,#0AH
POP
AX
POP
HL
REFERENCING THE ASSEMBLER
; Moves 2nd argument(l)
; Sets return value------------------------------------ (4)
; Restores base pointer----------------------------- (5)
RET------------------------------------------------------------------------------------------------------------------------- (6)
END
478
User’s Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
(1) Saving base pointer, work register
A label with ‘_’ prefixed to the function name described in the C source is described. Base pointers and
work registers are saved with the same name as function names described inside the C source.
After the label is described, the HL register (base pointer) is saved.
In the case of programs generated by the C compiler, other functions are called without saving the register
for register variables. Therefore, if changing the values of these registers for functions that are called, be
sure to save the values beforehand. However, if register variables are not used on the calling side, saving
the work register is not required.
(2) Copying to base pointer (HL) of stack pointer (SP)
The stack pointer (SP) changes due to ‘PUSH, POP’ inside functions. Therefore, the stack pointer is copied
to register ‘HL’ and used as the base pointer of arguments.
(3) Basic processing of FUNC function
After the processing in (1) and (2) is performed, the basic processing of called functions is performed.
(4) Setting the return value
If there is a return value, it is set in the ‘BC’ and ‘DE’ registers. If there is no return value, setting is
unnecessary.
BC register
Return value of 16 or fewer bits:
Word
DE register
Return value of 17 or more bits:
Higher word
BC register
Lower word
(5) Restoring the registers
Restore the saved base pointer and work register.
(6) Returning to the main function
Figure 12-2. Stack Area After Returning
low address
Return address to main
Stack pointer
Return value
BC register
Word
l (lower word)
Or
AX register
l (higher word)
DE register
BC register
Higher word
Lower word
i
high address
Stack area
User’s Manual U14872EJ1V0UM
479
CHAPTER 12
REFERENCING THE ASSEMBLER
12.4 Calling C Language Routines from Assembly Language
(1) Calling the C language function from an assembly language program
The procedure for calling a function written in the C language from an assembly language routine is:
(1) Place the arguments on the stack.
(2) Save the C work registers (AX, BC, and DE).
(3) Call the C language function.
(4) Increment the value of the stack pointer (SP) by the number of bytes of arguments.
(5) Reference the return value of the C language function (in BC or DE and BC).
This is an example of an assembly language program.
$PROCESSOR (9024)
NAME
FUNC2
EXTRN
_CSUB
PUBLIC _FUNC2
@@CODE CSEG
_FUNC2:
ax, #20H
; Sets 2nd argument (j)
push
ax
;
movw
ax, #21H
; Sets 1st argument (i)
call
!_CSUB
; Calls "CSUB (i, j)"
pop
ax
;
~
movw
ret
END
(1) Stacking arguments
Any arguments are placed on the stack. Figure 12-3 shows argument passing.
Figure 12-3. Placing Arguments on Stack
low address
CSUB (i, j)
AX register
1st arg
2nd arg
high address
Stack area
480
User’s Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
(2) Saving the work registers (AX, BC, and DE)
The three register pairs of AX, BC, and DE are used in the C language. Their values are not restored when
returning. Therefore, if the values in registers are needed, they are saved on the calling side.
Save or restore the registers before or after an argument pass code. The HL register is always saved on the
side of the C language when it is used in the C language.
(3) Calling a C language function
A CALL instruction calls a C language function. If the C language function is a callt function, the callt
instruction performs the call.
(4) Restoring the stack pointer (SP)
The stack pointer is restored by the number of bytes holding the arguments.
(5) Referencing the return value (BC and DE)
The return value from the C language is returned as follows.
BC register
Return value of 16 or fewer bits:
Word
DE register
Return value of 17 or more bits:
BC register
Higher word
Lower word
(2) Referencing arguments in a C language function
To correctly pass the i and j arguments to the C language program shown below, they are placed on the stack as
shown in Figure 12-4.
void CSUB (i, j)
int
i, j ;
{
i += j;
}
Figure 12-4. Passing Arguments to C Language
low address
CSUB (i, j)
Stack pointer
Return address to the calling side
AX register
i
j
high address
Stack area
User’s Manual U14872EJ1V0UM
481
CHAPTER 12
REFERENCING THE ASSEMBLER
12.5 Referencing Variables Defined in Other Languages
(1) Referencing variables defined in the C language
If external variables defined in a C language program are referenced in an assembly language routine, the
extern declaration is used. Underscores ‘_’ are added to the beginning of the variables defined in the assembly
language routine.
C language program example
extern void subf();
char
c = 0;
int
i = 0;
void main()
{
subf();
}
The following occurs in the RA78K0S assembler.
$PROCESSOR (9024)
PUBLIC _subf
EXTRN
_c
EXTRN
_i
@@CODE CSEG
_subf:
MOV
a, #04H
MOV
!_c, a
MOVW
ax, #07H
MOVW
de, #_i
INCW
DE
MOV
[DE], A
DECW
DE
XCH
A, X
MOV
[DE], A
;7
RET
END
482
User’s Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
(2) Referencing variables defined in the assembly language from the C language
Variables defined in assembly language are referenced from the C language in this way.
C language program example
extern char c;
extern int i;
void subf()
{
c = 'A' ;
i = 4 ;
}
The following occurs in the RA78K0S assembler.
NAME ASMSUB
PUBLIC
_c
PUBLIC
_i
ABC
CSEG
_c:
DB
0
_i:
DW
0
END
User’s Manual U14872EJ1V0UM
483
CHAPTER 12
REFERENCING THE ASSEMBLER
12.6 Cautions
(1) ‘_’ (underscore)
This C compiler adds an underscore ‘_’ (ASCII code ‘5FH’) to external definitions and reference names of the
object modules to be output. In the next C program example, “j = FUNC(i, l);” is taken as a reference to the
external name _FUNC.
/* Function prototype */
extern int FUNC(int, long);
void main()
{
int
i, j;
long
l;
i = 1;
l = 0x54321;
/* Function call */
j = FUNC(i, l);
}
The routine name is written as ‘_FUNC’ in RA78K0S.
(2) Argument positions on the stack
The arguments placed on the stack are placed from the postfix argument to the prefix argument in the direction
from the high address to the low address.
Figure 12-5. Stack Positions of Arguments
low address
AX register
Return address to main
j=FUNC(i, l);
Stack pointer
l (lower word)
l (higher word)
high address
Stack area
484
User’s Manual U14872EJ1V0UM
i
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
This chapter introduces how to effectively use this C compiler.
13.1 Efficient Coding
When developing 78K/0S Series application products, efficient object generation may be realized with this C
compiler by utilizing the saddr area or callt area of the device.
• Use external variables
if (saddr area is usable)
sreg/_ _sreg variables are used/
compiler option (-RD) is used
• Use 1-bit data
if (saddr area is usable)
bit/boolean/ _ _boolean type variables are used
• Function definition
if (function to be called several times)
if (callt area is usable)
Use as _ _callt/callt function (effective for reducing code size)
if (not used recursively)
Use as _ _leaf/norec function
if (automatic variables are not used)
Use as noauto function
if (automatic variables are used &&saddr area is usable)
register declaration
User’s Manual U14872EJ1V0UM
485
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
(1) Using external variable
When defining an external variable, specify the external variable to be defined as a sreg/_ _sreg variable if the
saddr area can be used. Instructions to sreg/_ _sreg variables are shorter in code length than instructions to
memory. This helps shorten object code and improve program execution speed. (The same can be also
performed by specifying the -RD option, instead of using the sreg variable.)
Definition of sreg/_ _sreg variable:
extern sreg int variable-name ;
extern_ _sreg int variable-name ;
Remark
Refer to 11.5 (3) How to use the saddr area.
(2) 1-bit data
A data object which only uses 1-bit data should be declared as a bit type variable (or boolean/_ _boolean type
variable). A bit manipulation instruction will be generated for an operation on bit/boolean/_ _boolean type
variables. Because the saddr area is used as well as the sreg variable, the codes can be shortened and the
execution speed can be improved.
Declaration of bit/boolean type variable:
bit variable-name ;
boolean variable-name ;
_ _boolean variable-name ;
Remark
Refer to 11.5 (7) bit type variables.
(3) Function definitions
For a function to be called repeatedly, object code should be shortened or a structure that allows calling at high
speeds should be provided. If the callt area can be used for functions to be called frequently, such functions
should be defined as callt functions. The callt function can be called faster than ordinary function calls with a
shorter code because the callt function is called using the callt area of the device.
Definition of callt function: callt int tsub() {
.
.
.
}
Remark
Refer to 11.5 (1) callt functions and 11.5 (6) norec function.
In addition to the use of the saddr area, objects that do not require modification of the C source by compiling
with optimization options can be generated. For the effect of each -Q suboption, refer to the CC78K0S C
Compiler Operation (U14871E).
486
User’s Manual U14872EJ1V0UM
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
(4) Optimization options
The optimization option that emphasizes the object code size the most is as follows.
[Object code is emphasized the most]
-QX3
The further shortening of the code size and the improvement of the execution speed is possible by adding _
_sreg to variables. However, this is restricted to cases when the saddr area can be used. If there is insufficient
area and the saddr area cannot be used, a compile error occurs.
To highly emphasize the execution speed, specify the -QX2 default.
In addition, the object efficiency can be improved by adding the extended functions supported by this compiler to
the C source.
(5) Using extended description
• Function definition
if (function to be called several times)
if (not used recursively)
Use as _ _leaf/norec function
if (automatic variables not used)
Use as noauto function
if (automatic variables are used && register/saddr area is usable)
register declaration
if (internal static variables are used) && (saddr area is usable)
_ _sreg declaration
• Functions not used recursively
Of the functions to be called repeatedly, the ones which are not used recursively should be defined as _
_leaf/norec functions. The norec function is a function that does not have preprocessing/ postprocessing
(stack frame). Therefore, the object code can be shortened and the execution speed can be improved
compared to ordinary functions.
Remark
For the definition of the norec function (norec int rout ()...), refer to 11.5 (6) norec function
and 11.7.4 norec function call interface.
User’s Manual U14872EJ1V0UM
487
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
• Functions that do not use automatic variables
Functions that do not use automatic variables should be defined as a noauto function. This function does not
output code for stack frame formation and its arguments are passed to registers as much as possible, which
helps shorten object code and improve program execution speed.
Remark
Refer to 11.5 (5)
noauto function, 11.7.3
noauto function call interface about noauto
function definition (noauto int sub1 (int i) ...).
• Functions that use automatic variables
If the saddr area can be used for a function that does not use automatic variables, declare the function with
the register storage class specifier. By this register declaration, the declared object will be allocated to a
register.
A program using registers operates faster than one using memory, and object code can be
shortened as well.
Remark
Refer to 11.5 (2) Register variables for the definition of register variables (register int i; ...).
• Functions that use internal static variables
If the saddr area can be used for a function that uses internal static variables, declare the function with
_ _sreg or specify the -RS option. In the same way as with sreg variables, the object code can be shortened
and the execution speed can be improved.
Remark
Refer to 11.5 (3) How to use the saddr area.
In addition, the code efficiency and the execution speed can be improved by the following method.
• Use of SFR name (or SFR bit name).
#pragma sfr
• Use of _ _sreg declaration for bit fields which consist only of 1-bit members (unsigned char type can be
used for members).
_ _sreg struct bf {
unsigned char a : 1 ;
unsigned char b : 1 ;
unsigned char c : 1 ;
unsigned char d : 1 ;
unsigned char e : 1 ;
unsigned char f : 1 ;
} bf_1 ;
• Use of multiplication and division embedded function.
#pragma mul
#pragma div
• Description of only the modules whose speed needs to be improved in the assembly language.
488
User’s Manual U14872EJ1V0UM
APPENDIX A
LIST OF LABELS FOR saddr AREA
In the CC78K0S, the saddr area is referenced by the following label names. Therefore, labels in the C source
program and in assembler source program that have the same names as the following labels cannot be used.
A.1 Normal Model
(a) Register variables
Label Name
Address
[email protected]
0FED8H
[email protected]
0FED9H
[email protected]
0FEDAH
[email protected]
0FEDBH
[email protected]
0FEDCH
[email protected]
0FEDDH
[email protected]
0FEDEH
[email protected]
0FEDFH
[email protected]
0FEE0H
[email protected]
0FEE1H
[email protected]
0FEE2H
[email protected]
0FEE3H
[email protected]
0FEE4HNote
[email protected]
0FEE5HNote
[email protected]
0FEE6HNote
[email protected]
0FEE7HNote
Note When the arguments of the function are declared by register or the -QV option is specified and the
-QR option is specified, arguments are allocated to the saddr area.
(b) Arguments of norec function
Label Name
[email protected]
Address
0FEE8H
[email protected]
0FEEAH
[email protected]
0FEECH
[email protected]
0FEEEH
User’s Manual U14872EJ1V0UM
489
APPENDIX A
LIST OF LABELS FOR saddr AREA
(c) Automatic variables of norec function
Label Name
Address
[email protected]
0FEF0H
[email protected]
0FEF1H
[email protected]
0FEF2H
[email protected]
0FEF3H
[email protected]
0FEF4H
[email protected]
0FEF5H
[email protected]
0FEF6H
[email protected]
0FEF7H
(d) Arguments of runtime library
Label Name
490
Address
[email protected]
0FEF8H
[email protected]
0FEF9H
[email protected]
0FEFAH
[email protected]
0FEFBH
[email protected]
0FEFCH
[email protected]
0FEFDH
[email protected]
0FEFEH
[email protected]
0FEFFH
User’s Manual U14872EJ1V0UM
APPENDIX A
LIST OF LABELS FOR saddr AREA
A.2 Static Model
(a) Shared area
Label Name
Address
[email protected]
0FEF0H
[email protected]
0FEF1H
[email protected]
0FEF2H
[email protected]
0FEF3H
[email protected]
0FEF4H
[email protected]
0FEF5H
[email protected]
0FEF6H
[email protected]
0FEF7H
[email protected]
0FEF8H
[email protected]
0FEF9H
[email protected]
0FEFAH
[email protected]
0FEFBH
[email protected]
0FEFCH
[email protected]
0FEFDH
[email protected]
0FEFEH
[email protected]
0FEFFH
(b) For arguments, automatic variables, and work
Label Name
Address
Note
[email protected]
0FExxH
[email protected]
[email protected] + 1
[email protected]
[email protected] + 2
[email protected]
[email protected] + 3
[email protected]
[email protected] + 4
[email protected]
[email protected] + 5
[email protected]
[email protected] + 6
[email protected]
[email protected] + 7
Note Arbitrary address in the saddr area
User’s Manual U14872EJ1V0UM
491
APPENDIX B
LIST OF SEGMENT NAMES
This chapter explains all the segments that the compiler outputs and their locations.
(1) and (2) show the option and re-allocation attributes used in the table.
This section describes all the segments that are output by the compiler.
<1> CSEG re-allocation attribute
CALLT0:
Allocates the specified segment so that the start address is a multiple of two within the
range of 40H to 7FH.
AT absolute expression: Allocates the specified segment to an absolute address (within the range of 0000H to
FEFFH).
FIXED:
Allocates the start address of the specified segment within the range of 800H to
0FFFH.
UNITP:
Allocates the specified segment so that the start address is a multiple of two within any
position (within the range of 80H to 0FA7EH).
<2> DSEG re-allocation attribute
SADDRP:
Allocates the specified segment so that the start address is a multiple of two within the
range of FE20H to FEFFH in the saddr area.
UNITP:
Allocates the specified segment so that the start address is a multiple of two within any
position (default is within the RAM area).
492
User’s Manual U14872EJ1V0UM
APPENDIX B
LIST OF SEGMENT NAMES
B.1 List of Segment Names
Section Name
Segment Type
Re-allocation Attribute
Description
@@CODE
CSEG
Segment for code portion
@@CNST
CSEG
Segment for const variable
@@R_INIT
CSEG
Segment for initialization data (with initial value)
@@R_INIS
CSEG
UNITP
Segment for initialization data (sreg variable with initial value)
@@CALT
CSEG
CALLT0
Segment for callt function table
@@VECTnn
CSEG
AT 00nnH
Segment for vector tableNote
@@INIT
DSEG
Segment for data area (with initial value)
@@DATA
DSEG
Segment for data area (without initial value)
@@INIS
DSEG
SADDRP
Segment for data area (sreg variable with initial value)
@@DATS
DSEG
SADDRP
Segment for data area (sreg variable without initial value)
@@BITS
BSEG
Segment for boolean-type and bit-type variables
Note The value of nn changes depending on the interrupt types.
B.2 Location of Segment
Segment Type
Destination of Allocation (Default)
CSEG
ROM
BSEG
saddr area of RAM
DSEG
RAM
User’s Manual U14872EJ1V0UM
493
APPENDIX B
LIST OF SEGMENT NAMES
B.3 Example of C Source
#pragma INTERRUPT INTP0 inter
/* Interrupt vector
*/
void inter (void) ;
/* Interrupt function prototype declaration */
const int i_cnst = 1 ;
/* const variable
*/
callt void f_clt (void) ;
/* callt function prototype declaration
*/
boolean b_bit ;
/* boolean-type variable
*/
long l_init = 2 ;
/* External variable with initial value
*/
int i_data ;
/* External variable without initial value
*/
sreg int sr_inis = 3 ;
/* sreg variable with initial value
*/
sreg int sr_dats ;
/* sreg variable without initial value
*/
void main ()
/* Function definition
*/
/* Interrupt function definition
*/
/* callt function definition
*/
{
int i ;
i = 100 ;
}
void inter ()
{
unsigned char uc = 0;
uc++;
if (b_bit)
b_bit = 0 ;
}
callt void f_clt ()
{
}
494
User’s Manual U14872EJ1V0UM
APPENDIX B
LIST OF SEGMENT NAMES
B.4 Example of Output Assembler Module
Quasi-directives and instruction sets in an assembler source vary depending on the device.
Refer to the RA78K0S Online Help for details.
; 78K/0S Series C Compiler V1.30 Assembler Source
;
Date:xx xxx xxxx Time:xx:xx:xx
; Command
: -c9026 sampk0s.c -sa -ng
; In-file
: sampk0s.c
; Asm-file
: sampk0s.asm
; Para-file :
$PROCESSOR(9026)
$NODEBUG
$NODEBUGA
$KANJICODE SJIS
$TOL_INF
03FH, 0130H, 00H, 00H
EXTRN
[email protected]
PUBLIC
_inter
PUBLIC
?f_clt
PUBLIC
_i_cnst
PUBLIC
_b_bit
PUBLIC
_l_init
PUBLIC
_i_data
PUBLIC
_sr_inis
PUBLIC
_sr_dats
PUBLIC
_main
PUBLIC
_f_clt
PUBLIC
[email protected]
@@BITS
BSEG
_b_bit
DBIT
@@CNST
CSEG
; Segment for boolean-type variables
; Segment for const variables
_i_cnst:
DW
@@R_INIT
CSEG
01H
; 1
; Segment for initialization data
(external variables with an initial value)
DW
@@INIT
00002H,00000H ; 2
; Segment for data area
DSEG
(external variables with an initial value)
_l_init:
@@DATA
DSEG
DS
(4)
; Segment for data area
(external variables without an initial value)
User’s Manual U14872EJ1V0UM
495
APPENDIX B
_i_data:
DS
(2)
@@R_INIS
CSEG
UNITP
LIST OF SEGMENT NAMES
; Segment for initialization data
(sreg variables with an initial value)
@@INIS
DW
03H
DSEG
SADDRP
; 3
; Segment for data area
(sreg variables with an initial value)
_sr_inis:
DS
@@DATS
SADDRP
DSEG
(2)
; Segment for data area
(sreg variables without an initial value)
_sr_dats:
@@CALT
DS
CSEG
?f_clt: DW
(2)
; Segment for the callt function
CALLT0
_f_clt
/*Interrupt vector*/
; line
1 : #pragma INTERRUPT INTP0 inter
; line
2 :
; line
3 : void inter(void);
/*Interrupt function prototype declaration*/
; line
4 : const int i_cnst=1;
/*const variable*/
; line
5 : callt void f_clt(void);
/*callt function prototype declaration*/
; line
6 : boolean b_bit;
/*boolean-type variable*/
; line
7 : long l_init=2;
/*External variable with an initial value*/
; line
8 : int i_data;
/*External variable without an initial value*/
; line
9 : sreg int sr_inis=3;
/*sreg variable with an initial value */
; line
10 : sreg int sr_dats;
; line
11 :
; line
12 : void main()
; line
13 : {
@@CODE
/*sreg variable without an initial value */
/*Function definition*/
; Segment for code block
CSEG
_main:
push
hl
;[INF] 1, 4
movw
ax,#02H
;[INF] 3, 6
callt
[[email protected]]
;[INF] 1, 8
; line
14 :
int
; line
15 :
i=100;
; line
i;
movw
ax,#064H
; 100
;[INF] 3, 6
mov
[hl+1],a
; i
;[INF] 2, 6
xch
a,x
;[INF] 1, 4
mov
[hl],a ; i
;[INF] 1, 6
16 : }
pop
ax
;[INF] 1, 6
pop
hl
;[INF] 1, 6
ret
496
; line
17 :
; line
18 : void inter()
;[INF] 1, 6
/*Interrupt function definition*/
User’s Manual U14872EJ1V0UM
APPENDIX B
; line
LIST OF SEGMENT NAMES
19 : {
_inter:
push
ax
;[INF] 1, 4
push
de
;[INF] 1, 4
push
hl
;[INF] 1, 4
movw
ax,#02H
;[INF] 3, 6
[[email protected]]
;[INF] 1, 8
callt
; line
20 :
unsigned char uc=0;
xor
a,a
mov
[hl+1],a
; line
21 :
inc
xch
; line
;[INF] 2, 6
uc++;
a
;[INF] 2, 4
a,[hl+1]
22 :
if(b_bit)
23 :
b_bit=0;
bf
; line
;[INF] 2, 4
; uc
; uc
;[INF] 2, 8
_b_bit,$L0005
clr1
;[INF] 4,10
_b_bit
;[INF] 3, 6
L0005:
; line
24 : }
pop
ax
;[INF] 1, 6
pop
hl
;[INF] 1, 6
pop
de
;[INF] 1, 6
pop
ax
;[INF] 1, 6
reti
;[INF] 1, 8
; line
25 :
; line
26 : callt void f_clt()
; line
27 : {
/*callt function definition */
_f_clt:
; line
28 : }
ret
@@VECT06
;[INF] 1, 6
CSEG
AT
0006H
; Interrupt vector
[email protected]:
DW
_inter
END
; *** Code Information ***
;
; $FILE C:\NECTools32\work\sampk0s.c
;
; $FUNC main(13)
;
void=(void)
;
CODE SIZE= 15 bytes, CLOCK_SIZE= 58 clocks, STACK_SIZE= 6 bytes
;
; $FUNC inter(19)
;
void=(void)
;
CODE SIZE= 27 bytes, CLOCK_SIZE= 96 clocks, STACK_SIZE= 10 bytes
User’s Manual U14872EJ1V0UM
497
APPENDIX B
LIST OF SEGMENT NAMES
;
; $FUNC f_clt(27)
;
void=(void)
;
CODE SIZE= 1 bytes, CLOCK_SIZE= 6 clocks, STACK_SIZE= 0 bytes
; Target chip : uPD78926
; Device file : Vx.xx
498
User’s Manual U14872EJ1V0UM
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1 shows the runtime library list.
These operational instructions are called in the format where @@, etc. are attached at the beginning of the
function name.
However, cstart, cprep, and cdisp are called in the format with [email protected] attached to the beginning.
No library support is available for operations not in Table C-1. The compiler executes inline expansion.
long addition and subtraction, and/or/xor and shift may be expanded inline.
Table C-1. List of Runtime Libraries (1/6)
Classification
Increment
Decrement
Sign reverse
1’s complement
Logical NOT
Multiply
Divide
Function
Name
Supported Model
Function
Normal Model
Static Model
lsinc
√
−
Increments signed long
luinc
√
−
Increments unsigned long
finc
√
−
Increments float
lsdec
√
−
Decrements signed long
ludec
√
−
Decrements unsigned long
fdec
√
−
Decrements float
lsrev
√
−
Reverses the sign of signed long
lurev
√
−
Reverses the sign of unsigned long
frev
√
−
Reverses the sign of float
lscom
√
−
Obtains 1’s complement of signed long
lucom
√
−
Obtains 1’s complement of unsigned long
lsnot
√
−
Negates signed long
lunot
√
−
Negates unsigned long
fnot
√
−
Negates float
csmul
√
√
Performs multiplication between signed char data
cumul
√
√
Performs multiplication between unsigned char data
ismul
√
√
Performs multiplication between signed int data
iumul
√
√
Performs multiplication between unsigned int data
lsmul
√
−
Performs multiplication between signed long data
lumul
√
−
Performs multiplication between unsigned long data
fmul
√
−
Performs multiplication between float data
csdiv
√
√
Performs division between signed char data
cudiv
√
√
Performs division between unsigned char data
isdiv
√
√
Performs division between signed int data
iudiv
√
√
Performs division between unsigned int data
lsdiv
√
−
Performs division between signed long data
ludiv
√
−
Performs division between unsigned long data
fdiv
√
−
Performs division between float data
User’s Manual U14872EJ1V0UM
499
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (2/6)
Classification
Remainder
Add
Subtract
Shift left
Shift right
Function
Name
Supported Model
Function
Normal Model
Static Model
csrem
√
√
Obtains remainder after division between signed char data
curem
√
√
Obtains remainder after division between unsigned char
data
isrem
√
√
Obtains remainder after division between signed int data
iurem
√
√
Obtains remainder after division between unsigned int
data
lsrem
√
−
Obtains remainder after division between signed long data
lurem
√
−
Obtains remainder after division between unsigned long
data
lsadd
√
−
Performs addition between signed long data
luadd
√
−
Performs addition between unsigned long data
fadd
√
−
Performs addition between float data
lssub
√
−
Performs subtraction between signed long data
lusub
√
−
Performs subtraction between unsigned long data
fsub
√
−
Performs subtraction between float data
islsh
√
√
Shifts signed int data to the left
iulsh
√
√
Shifts unsigned int data to the left
lslsh
√
−
Shifts singed long data to the left
lulsh
√
−
Shifts unsigned long data to the left
isrsh
√
√
Shifts signed int data to the right
iursh
√
√
Shifts unsigned int data to the right
lsrsh
√
−
Shifts signed long data to the right
lursh
√
−
Shifts unsigned long data to the right
cscmp
√
√
Compares signed char data
iscmp
√
√
Compares signed int data
lscmp
√
−
Compares signed long data
lucmp
√
−
Compares unsigned long data
fcmp
√
−
Compares float data
Bit AND
lsband
√
−
Performs an AND operation between signed long data
luband
√
−
Performs an AND operation between unsigned long data
Bit OR
lsbor
√
−
Performs an OR operation between signed long data
lubor
√
−
Performs an OR operation between unsigned long data
Bit XOR
lsbxor
√
−
Performs an XOR operation between signed long data
lubxor
√
−
Performs an XOR operation between unsigned long data
Logical AND
fand
√
−
Performs a logical AND operation between two float data
Logical OR
for
√
−
Performs a logical OR operation between two float data
Conversion from
floating-point
number
ftols
√
−
Converts from float to signed long
ftolu
√
−
Converts from float to unsigned long
Conversion to
floating-point
number
lstof
√
−
Converts from signed long to float
lutof
√
−
Converts from unsigned long to float
Conversion from
bit
btol
√
−
Converts from bit to long
Compare
500
User’s Manual U14872EJ1V0UM
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (3/6)
Classification
Startup routine
Function
Name
cstart
Supported Model
Normal Model
Static Model
√
√
Function
Startup module
• After an area (2 × 32 bytes) where a function that will be
registered is reserved with the atexit function, sets the
beginning label name to [email protected]
• Reserve a break area (32 bytes), sets the beginning
label name to [email protected], and then sets the next label
name of the area to [email protected]
• Define the segment in the reset vector table as follows,
and set the beginning address of the startup module.
@@VECT00
CSEG
AT 0000H
DW
[email protected]
• Set 0 to the variable _errno to which the error number is
input.
• Set the variable [email protected], to which the number of
functions registered by the atexit function is input, to 0.
• Set the address of [email protected] to the variable
[email protected] as the initial break value.
• Set 1 as the initial value for the variable [email protected], which
is the source of pseudo random numbers for the rand
function.
• Perform copy processing of initialized data and execute
0 clear of external data without an initial value.
• Call the main function (user program)
• Call the exit function by parameter 0.
Pre- and postprocessing of
function
cprep
√
−
Preprocessing of function
cdisp
√
−
Postprocessing of function
cprep2
√
−
Preprocessing of function (including the saddr area for
register variables)
cdisp2
√
−
Postprocessing of function (including the saddr area for
register variables)
nrcp2
−
√
nrcp3
−
√
krcp2
−
√
krcp3
−
√
nkrc3
−
√
nrip2
−
√
nrip3
−
√
krip2
−
√
krip3
−
√
nkri31
−
√
nkri32
−
√
nrsave
−
√
For saving [email protected]
nrload
−
√
For restoring [email protected]
For copying arguments
User’s Manual U14872EJ1V0UM
501
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (4/6)
Classification
Pre- and postprocessing of
function
BCD-type
conversion
Auxiliary
502
Function
Name
Supported Model
Function
Normal Model
Static Model
krs02
−
√
krs04
−
√
krs04i
−
√
krs06
−
√
krs06i
−
√
krs08
−
√
krs08i
−
√
krs10
−
√
krs10i
−
√
krs12
−
√
krs12i
−
√
krs14
−
√
krs14i
−
√
krs16
−
√
krs16i
−
√
krl02
−
√
krl04
−
√
krl04i
−
√
krl06
−
√
krl06i
−
√
krl08
−
√
krl08i
−
√
krl10
−
√
krl10i
−
√
krl12
−
√
krl12i
−
√
krl14
−
√
krl14i
−
√
krl16
−
√
krl16i
−
√
hdwinit
√
√
Performs initialization processing of peripheral devices (sfr)
immediately after CPU reset.
bcdtob
√
√
Converts 1-byte bcd to 1-byte binary
btobcd
√
√
Converts 1-byte binary to 2-byte bcd
bcdtow
√
√
Converts 2-byte bcd to 2-byte binary
wtobcd
√
√
Converts 2-byte binary to 2-byte bcd
For saving [email protected]
For restoring [email protected]
bbcd
√
√
Converts 1-byte binary to 1-byte bcd
mulu
√
√
K0mulu instruction-compatible
divuw
√
√
K0divuw instruction-compatible
User’s Manual U14872EJ1V0UM
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (5/6)
Classification
Auxiliary
Function
Name
Supported Model
Normal Model
Static Model
clra0
√
√
clra1
√
√
clrax0
√
√
clrax1
√
√
clrbc0
√
√
clrbc1
√
√
cmpa0
√
√
cmpa1
√
√
cmpc0
√
√
cmpax0
√
√
cmpax1
√
√
movca
√
√
movac
√
√
ctoi
√
√
uctoi
√
√
adjba
√
√
adjbs
√
√
addrde
√
√
addrhl
√
√
shl4
√
√
shr4
√
√
tabled
√
√
tableh
√
√
apdecd
√
√
apdech
√
√
apincd
√
√
apinch
√
√
deilo
√
√
deist
√
√
deiinc
√
√
deidec
√
√
hlilo
√
√
hlist
√
√
hliinc
√
√
hlidec
√
√
dellab
√
−
dell03
√
−
della4
√
−
delsab
√
−
dels03
√
−
Function
For replacing the fixed-type instruction pattern
User’s Manual U14872EJ1V0UM
503
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (6/6)
Classification
Auxiliary
504
Function
Name
Supported Model
Normal Model
Static Model
hlllab
√
−
hlll03
√
−
hllla4
√
−
hllsab
√
−
hlls03
√
−
hliadd
√
√
hlisub
√
√
hlicmp
√
√
hliand
√
√
hlior
√
√
hlixor
√
√
imule
√
√
isdive
√
√
iudive
√
√
isreme
√
√
iureme
√
√
iadde
√
√
isube
√
√
iande
√
√
iore
√
√
ixore
√
√
Function
For replacing the fixed-type instruction pattern
User’s Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1 shows the number of stacks consumed from the standard libraries.
Table D-1. List of Standard Library Stack Consumption (1/4)
Classification
ctype.h
setjmp.h
stdarg.h
stdio.h
Function Name
Static Model
isalnum
0
0
isalpha
0
0
iscntrl
0
0
isdigit
0
0
isgraph
0
0
islower
0
0
isprint
0
0
ispunct
0
0
isspace
0
0
isupper
0
0
isxdigit
0
0
tolower
0
0
toupper
0
0
isascii
0
0
toascii
0
0
_tolower
0
0
_toupper
0
0
tolow
0
0
toup
0
0
setjmp
4
4
longjmp
2
2
va_arg
0
—
va_start
0
—
va_end
0
sprintf
—
Note 1
52 (72)
Note 1
—
sscanf
290 (304)
—
printf
54 (72)Note 1
—
scanf
stdlib.h
Normal Model
Note 1
294 (304)
—
vprintf
Note 1
52 (72)
—
vsprintf
52 (72)Note 1
—
getchar
0
0
gets
6
6
putchar
0
0
puts
4
4
atoi
4
4
atol
10
—
strtol
20
—
User’s Manual U14872EJ1V0UM
505
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1. List of Standard Library Stack Consumption (2/4)
Classification
stdlib.h
string.h
506
Function Name
Normal Model
Static Model
strtoul
20
—
calloc
14
14
free
8
8
malloc
6
6
realloc
12
12
abort
0
0
atexit
0
0
Note 2
exit
2+n
2 + nNote 2
abs
0
0
div
6
—
labs
2
—
ldiv
16
—
brk
0
0
sbrk
4
4
atof
33
—
strtod
33
—
itoa
10
10
ltoa
16
—
ultoa
16
—
rand
16
—
srand
0
—
bsearch
32 + nNote 3
—
Note 4
qsort
16 + n
—
strbrk
0
0
strsbrk
4
4
stritoa
10
10
strltoa
16
—
strultoa
16
—
memcpy
4
6
memmove
4
8
strcpy
2
4
strncpy
4
6
strcat
2
4
strncat
4
6
memcmp
2
4
strcmp
2
2
strncmp
2
4
memchr
2
2
strchr
2
0
strcspn
6
6
strpbrk
4
4
User’s Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1. List of Standard Library Stack Consumption (3/4)
Classification
string.h
math.h
Function Name
Normal Model
Static Model
strrchr
4
4
strspn
6
6
strstr
4
4
strtok
4
4
memset
4
4
strerror
0
0
strlen
0
0
strcoll
2
2
strxfrm
4
4
acos
24
—
asin
24
—
atan
20
—
atan2
21
—
cos
Note 5
24 (34)
—
sin
24 (34)Note 5
—
tan
Note 5
—
26 (34)
cosh
24
—
sinh
25
—
tanh
30
—
exp
22
—
frexp
Note 5
2 (10)
—
ldexp
2 (10)Note 5
—
log
Note 5
—
Note 5
24 (34)
log10
24 (34)
—
modf
2 (10)Note 5
—
pow
Note 5
25 (35)
—
sqrt
18
—
ceil
2
—
fabs
0
—
floor
2
—
frmod
2 (10)Note 5
—
matherr
0
—
acosf
24
—
asinf
24
—
atanf
20
—
atan2f
21
—
cosf
Note 5
24 (34)
—
sinf
24 (34)Note 5
—
tanf
Note 5
—
26 (34)
coshf
24
—
sinhf
25
—
User’s Manual U14872EJ1V0UM
507
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1. List of Standard Library Stack Consumption (4/4)
Classification
math.h
Function Name
Static Model
tanhf
30
—
expf
22
—
frexpf
2 (10)Note 5
—
ldexpf
Note 5
2 (10)
—
logf
24 (34)Note 5
—
log10f
24 (34)Note 5
—
modff
assert.h
Normal Model
Note 5
2 (10)
Note 5
—
powf
25 (35)
—
sqrtf
18
—
ceilf
2
—
fabsf
0
—
floorf
2
—
fmodf
2 (10)Note 5
_ _assertfail
Note 6
66 (84)
—
—
Notes 1. Values in parentheses are for when a version that supports floating-point numbers is used.
2. n is the total stack consumption among external functions registered by the atexit function.
3. n is the stack consumption of external functions called from bsearch.
4. n is (20 + stack consumption of external functions called from qsort) × (1 + number of times recursive
calls occurred).
5. Values in parentheses are for when an operation exception occurs.
6. Values in parentheses are for when the printf version that supports floating-point numbers is used.
508
User’s Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2 shows the number of stacks consumed from the runtime libraries.
Table D-2. List of Runtime Library Stack Consumption (1/5)
Classification
Increment
Function Name
Normal Model
Static Model
lsinc
0
luinc
0
finc
12 (22)
—
lsdec
0
—
ludec
0
fdec
12 (22)
—
lsrev
0
—
lurev
0
—
frev
0
—
1’s complement
lscom
0
—
lucom
0
—
Logical NOT
lsnot
0
—
lunot
0
—
Decrement
Sign reverse
Multiply
Divide
Remainder
Add
Subtract
—
—
Note 1
—
Note 1
fnot
0
—
csmul
4
4
cumul
4
4
ismul
6
6
iumul
6
6
lsmul
6
—
lumul
6
—
Note 1
fmul
8 (18)
—
csdiv
8
8
cudiv
4
4
isdiv
8
12
iudiv
4
6
lsdiv
10
—
ludiv
6
fdiv
8 (18)
—
csrem
8
8
curem
4
4
—
Note 1
isrem
8
12
iurem
4
6
lsrem
10
—
lurem
6
—
lsadd
0
—
luadd
0
—
Note 1
fadd
8 (18)
—
lssub
0
—
lusub
0
fsub
—
Note 1
8 (18)
User’s Manual U14872EJ1V0UM
—
509
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (2/5)
Classification
Shift left
Shift right
Compare
Bit AND
Bit OR
Bit XOR
Function Name
Normal Model
Static Model
islsh
0
0
iulsh
0
0
lslsh
2
—
—
lulsh
2
isrsh
0
0
iursh
0
0
lsrsh
2
—
lursh
2
—
cscmp
0
2
iscmp
0
2
lscmp
2
—
lucmp
2
—
fcmp
4 (14)Note 1
—
lsband
0
—
luband
0
—
lsbor
0
—
lubor
0
—
lsbxor
0
—
lubxor
0
—
Logical AND
fand
0
—
Logical OR
for
0
—
Conversion from
floating-point number
ftols
4
—
ftolu
4
—
Conversion to
floating-point number
lstof
12 (22)Note 1
—
lutof
12 (22)Note 1
—
Conversion from bit
btol
0
—
Startup routine
cstart
2
Pre- and postprocessing of function
510
2
Note 2
cprep
2+n
—
cdisp
0
—
cprep2
Size of automatic variable + register
variable
—
cdisp2
0
—
nrcp2
—
0
nrcp3
—
0
krcp2
—
0
krcp3
—
0
nkrc3
—
0
nrip2
—
0
nrip3
—
0
krip2
—
0
krip3
—
0
nkri31
—
0
nkri32
—
0
nrsave
—
8
nrload
—
0
User’s Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (3/5)
Classification
Pre- and postprocessing of function
BCD-type conversion
Auxiliary
Function Name
Normal Model
Static Model
krs02
—
2
krs04
—
4
krs04i
—
4
krs06
—
6
krs06i
—
6
krs08
—
8
krs08i
—
8
krs10
—
10
krs10i
—
10
krs12
—
12
krs12i
—
12
krs14
—
14
krs14i
—
14
krs16
—
16
krs16i
—
16
krl02
—
0
krl04
—
0
krl04i
—
0
krl06
—
0
krl06i
—
0
krl08
—
0
krl08i
—
0
krl10
—
0
krl10i
—
0
krl12
—
0
krl12i
—
0
krl14
—
0
krl14i
—
0
krl16
—
0
krl16i
—
0
hdwinit
0
0
bcdtob
4
4
btobcd
8
8
bcdtow
4
4
wtobcd
10
10
bbcd
8
8
mulu
4
4
divuw
6
6
User’s Manual U14872EJ1V0UM
511
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (4/5)
Classification
Auxiliary
512
Function Name
Normal Model
Static Model
clra0
0
0
clra1
0
0
clrax0
0
0
clrax1
0
0
clrbc0
0
0
clrbc1
0
0
cmpa0
0
0
cmpa1
0
0
cmpc0
0
0
cmpax0
0
0
cmpax1
0
0
movca
0
0
movac
0
0
ctoi
0
0
uctoi
0
0
adjba
2
2
adjbs
1
1
addrde
0
0
addrhl
0
0
shl4
0
0
shr4
0
0
tabled
0
0
tableh
0
0
apdecd
0
0
apdech
0
0
apincd
0
0
apinch
0
0
deilo
0
0
deist
0
0
deiinc
0
0
deidec
0
0
hlilo
0
0
hlist
0
0
hliinc
0
0
hlidec
0
0
dellab
2
—
dell03
0
—
della4
0
—
delsab
0
—
dels03
2
—
hlllab
0
—
hlll03
0
—
User’s Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (5/5)
Classification
Auxiliary
Function Name
Normal Model
Static Model
hllla4
0
—
hllsab
0
—
hlls03
0
—
hliadd
0
0
hlisub
0
0
hlicmp
0
0
hliand
0
0
hlior
0
0
hlixor
0
0
imule
10
10
isdive
12
16
iudive
8
10
isreme
12
16
iureme
8
10
iadde
0
0
isube
2
2
iande
0
0
iore
0
0
ixore
0
0
Notes 1. Values in parentheses are for when an operation exception occurs (when the matherr function
included with the compiler is used).
2. n is the size of the automatic variable to be secured.
User’s Manual U14872EJ1V0UM
513
APPENDIX E INDEX
\a .............................................................................. 36
_toupper .................................................................190
\b ............................................................................. 36
?? .............................................................................36
\f ............................................................................. 36
-QL option...............................................................310
\n ............................................................................. 36
-ZR option...............................................................405
\r ............................................................................. 36
A
\t ............................................................................. 36
\v ............................................................................. 36
#asm - #endasm .................................................... 339
#define directive..................................................... 155
#include.................................................................... 52
#include directive ................................................... 150
# operator............................................................... 153
## operator............................................................. 153
#pragma access..................................................... 356
#pragma asm ......................................................... 339
#pragma bcd .......................................................... 390
#pragma di ............................................................. 351
#pragma directive .................................................. 306
#pragma div ........................................................... 387
#pragma ei ............................................................. 351
#pragma halt .......................................................... 354
#pragma inline ....................................................... 415
#pragma interrupt................................................... 342
#pragma mul .......................................................... 385
#pragma name....................................................... 381
#pragma nop.......................................................... 354
#pragma opc .......................................................... 394
#pragma realregister.............................................. 411
#pragma rot............................................................ 382
#pragma section .................................................... 368
#pragma sfr............................................................ 323
#pragma stop ......................................................... 354
#pragma vect ......................................................... 342
_ _asm ................................................................... 339
_ _assertfail............................................................ 295
_ _boolean ............................................................. 335
_ _callt .................................................................... 309
abort .......................................................................220
abs..........................................................................222
Absolute address access function....................31, 356
Absolute address allocation specification.........33, 418
acos........................................................................250
acosf.......................................................................273
Aggregate type .........................................................46
ANSI .......................................................................300
Arithmetic operators .................................................90
Arrangement offset calculation simplification method
......................................................................33, 409
Array .......................................................................133
Array declarator ........................................................63
Array type .................................................................47
asin.........................................................................251
asinf........................................................................274
ASM statements ...............................................31, 339
Assembly language ..................................................21
assert......................................................................185
Assignment operators ............................................107
atan ........................................................................252
atan2 ......................................................................253
atan2f .....................................................................276
atanf .......................................................................275
atexit ...............................................................185, 221
atof .................................................................185, 225
atoi..........................................................................211
atol..........................................................................211
auto ..........................................................................54
Automatic pascal functionization of function call
interface ........................................................32, 405
_ _DATE_ _............................................................ 161
_ _FILE_ _ ............................................................. 161
B
_ _interrupt............................................................. 349
_ _LINE_ _ ............................................................. 161
BCD operation function ....................................32, 390
_ _OPC .................................................................. 394
Binary constant.................................................32, 379
_ _pascal.................................................................. 37
Bit field....................................................................360
_ _STDC_ _ ........................................................... 161
Bit field declaration ...........................................31, 360
_ _TIME_ _............................................................. 161
bit type variables...............................................31, 335
514
User’s Manual U14872EJ1V0UM
APPENDIX E
Bitwise AND operator............................................. 100
INDEX
do statement ..........................................................124
Bitwise inclusive OR operator ................................ 102
E
Bitwise XOR operator ............................................ 101
Block scope ............................................................. 40
boolean type variables..................................... 31, 335
Branch statement................................................... 112
break statement ..................................................... 129
brk.................................................................. 185, 224
bsearch .................................................................. 229
EI............................................................................351
Enumeration constant ..............................................50
Enumeration type .....................................................43
Enumeration type specifier.......................................59
Equality operators ....................................................98
errno.......................................................................178
C
error........................................................................178
C language .............................................................. 21
exit..................................................................185, 221
calloc...................................................................... 216
exp..........................................................................260
callt functions ................................................... 30, 309
expf.........................................................................283
Cast operator ........................................................... 89
Expression statement.............................................112
ceil ......................................................................... 268
extern .......................................................................54
ceilf ........................................................................ 291
External definition...................................................137
Changing compiler output section name ............... 368
External linkage........................................................40
char type .................................................................. 42
External object definitions ......................................140
ESCAPE sequence ..................................................36
Character constant .................................................. 51
F
Character type ......................................................... 46
Comma operator.................................................... 110
Comment ................................................................. 52
Compatible type....................................................... 48
Composite type........................................................ 48
Compound assignment.......................................... 109
Compound statement ............................................ 112
Conditional operators............................................. 106
const ........................................................................ 61
Constant .................................................................. 49
Constant expressions ............................................ 111
continue statement ................................................ 128
cos ......................................................................... 254
cosf ........................................................................ 277
cosh ....................................................................... 257
coshf ...................................................................... 280
CPU control instruction .................................... 31, 354
ctype ...................................................................... 172
fabs ........................................................................269
fabsf .......................................................................292
File scope.................................................................39
float ........................................................................183
Floating-point constant.............................................49
Floating-point type....................................................43
floor ........................................................................270
floorf .......................................................................293
fmod .......................................................................271
fmodf ......................................................................294
for statement ..........................................................125
free .........................................................................217
frexp .......................................................................261
frexpf ......................................................................284
Function declarator ..................................................63
Function definitions ................................................138
Function prototype scope.........................................40
D
Function scope.........................................................39
Data insertion function ..................................... 32, 394
Function type......................................................41, 47
Decimal constant ..................................................... 49
Functions..................................................................25
Function to change compiler output section name...32
Delimiter................................................................... 52
G
Device type ............................................................ 161
DI ........................................................................... 351
div .................................................................. 185, 223
Division function............................................... 32, 387
General integral promotion.......................................72
getchar ...................................................................207
gets ........................................................................208
User’s Manual U14872EJ1V0UM
515
APPENDIX E
goto statement ....................................................... 127
INDEX
logf..........................................................................286
Logical AND operator .............................................104
H
Logical OR operator ...............................................105
HALT...................................................................... 354
Header file.............................................................. 171
longjmp...........................................................185, 191
ltoa..........................................................................227
Header name ........................................................... 52
M
Hexadecimal constant.............................................. 50
Machine language ....................................................21
I
Macro name............................................................161
Identifier ................................................................... 38
if ... else statement................................................. 120
Incomplete type.................................................. 41, 46
Integral type ............................................................. 42
Internal linkage......................................................... 40
Interrupt function .............................................. 31, 351
Interrupt function qualifier ................................ 31, 349
Interrupt functions ............................................ 31, 342
isalnum................................................................... 187
isalpha.................................................................... 187
isascii ..................................................................... 187
iscntrl...................................................................... 187
isdigit...................................................................... 187
isgraph ................................................................... 187
islower.................................................................... 187
isprint ..................................................................... 187
ispunct.................................................................... 187
Macro replacement.................................................153
malloc .....................................................................218
math .......................................................................181
matherr ...................................................................272
memchr ..................................................................239
memcmp.................................................................237
memcpy..................................................................234
memmove...............................................................234
Memory manipulation function..........................33, 415
Memory space ........................................................304
memset...................................................................245
Method of int expansion limitation of argument/return
values............................................................33, 406
modf .......................................................................265
modff ......................................................................288
Module name changing function.......................32, 381
Multiplication function .......................................32, 385
isspace................................................................... 187
N
isupper ................................................................... 187
isxdigit .................................................................... 187
No linkage ................................................................40
Iteration statement ................................................. 112
noauto function.......................................................326
itoa ......................................................................... 227
noauto functions .......................................................31
NOP........................................................................354
K
norec function.........................................................330
Keywords ................................................................. 37
norec functions .........................................................31
O
L
Labeled statement ................................................. 112
labs ........................................................................ 222
Object type ...............................................................41
Octal constant ..........................................................50
ldexp ...................................................................... 262
P
ldexpf ..................................................................... 285
ldiv.................................................................. 185, 223
Pascal function .................................................32, 402
Library supporting prologue/epilogue............... 33, 435
Pascal function call interface..................................465
limits....................................................................... 178
peekb......................................................................356
log .......................................................................... 263
peekw .....................................................................356
log10 ...................................................................... 264
Pointer ....................................................................133
log10f ..................................................................... 287
Pointer declarator .....................................................62
516
User’s Manual U14872EJ1V0UM
APPENDIX E
INDEX
Pointer type.............................................................. 47
sprintf .............................................................185, 194
pokeb ..................................................................... 356
sqrt .........................................................................267
pokew .................................................................... 356
sqrtf ........................................................................290
Postfix operators ...................................................... 78
srand ..............................................................185, 228
pow ........................................................................ 266
sreg declaration......................................................316
powf ....................................................................... 289
sscanf.............................................................185, 199
Preprocessing directive ......................................... 141
Stack change specification.....................................345
printf............................................................... 185, 203
Startup routine........................................................375
putchar................................................................... 209
Start-up routine ......................................................296
puts ........................................................................ 210
static.........................................................................54
Static model .....................................................32, 396
Q
Static model expansion specification ...............33, 422
qsort....................................................................... 230
stdarg .....................................................................174
stddef .....................................................................180
stdio........................................................................174
R
stdlib.......................................................................175
rand................................................................ 185, 228
STOP......................................................................354
realloc .................................................................... 219
Storage class specifier .............................................54
Re-entrant.............................................................. 185
strbrk ......................................................................231
register............................................................. 54, 312
strcat ......................................................................236
Register bank......................................................... 304
strchr ......................................................................240
Register direct reference function.................... 33, 411
strcmp ....................................................................238
Register variables ............................................ 30, 312
strcoll......................................................................248
Relational operators................................................. 95
strcpy......................................................................235
return statement..................................................... 130
strcspn....................................................................241
rolb......................................................................... 382
strerror....................................................................246
rolw ........................................................................ 382
string ......................................................................177
ROMization-related section name.......................... 375
String literal ..............................................................51
rorb ........................................................................ 382
stritoa .....................................................................233
rorw........................................................................ 382
strlen ......................................................................247
Rotate function................................................. 32, 382
strltoa .....................................................................233
RTOS ..................................................................... 300
strncat ....................................................................236
strncmp ..................................................................238
S
strncpy....................................................................235
sbrk ................................................................ 185, 224
strpbrk ....................................................................242
Scalar type............................................................... 47
strrchr .....................................................................240
scanf .............................................................. 185, 204
strsbrk ....................................................................232
Selection statement ............................................... 112
strspn .....................................................................241
setjmp .................................................... 173, 185, 191
strstr .......................................................................243
sfr area............................................................. 30, 323
strtod ..............................................................185, 225
sfr variable ............................................................. 323
strtok ..............................................................185, 244
Shift operators ......................................................... 93
strtol .......................................................................213
Signed integral type ................................................. 43
strtoul .....................................................................213
Simple assignment ................................................ 108
struct ......................................................................132
sin .......................................................................... 255
Structure.................................................................132
sinf ......................................................................... 278
Structure pointers...................................................133
sinh ........................................................................ 258
Structure specifier ....................................................57
sinhf ....................................................................... 281
Structure type ...........................................................47
User’s Manual U14872EJ1V0UM
517
APPENDIX E
INDEX
U
Structure variable................................................... 132
strultoa ................................................................... 233
strxfrm .................................................................... 249
switch statement .................................................... 121
ultoa........................................................................227
Unary operators........................................................84
union.......................................................................134
T
Union ......................................................................134
Tags ......................................................................... 60
Unsigned integral type..............................................43
tan .......................................................................... 256
Usage of saddr area ...............................................316
tanf ......................................................................... 279
Usage of saddr area .................................................30
Union type ................................................................47
tanh ........................................................................ 259
V
tanhf ....................................................................... 282
Temporary variables ........................................ 33, 432
toascii..................................................................... 189
tolow....................................................................... 190
tolower ................................................................... 188
toup ........................................................................ 190
toupper................................................................... 188
Trigraph sequence ................................................... 36
Type modification............................................. 32, 400
Type names ............................................................. 64
va_arg.....................................................................192
va_end....................................................................192
va_start...................................................................192
void ...........................................................................74
void pointer ...............................................................74
volatile ......................................................................61
vprintf..............................................................185, 205
vsprintf ............................................................185, 206
Type specifier........................................................... 55
W
typedef ..................................................................... 54
while statement.......................................................123
518
User’s Manual U14872EJ1V0UM
[MEMO]
User’s Manual U14872EJ1V0UM
519
Facsimile Message
From:
Name
Company
Tel.
Although NEC has taken all possible steps
to ensure that the documentation supplied
to our customers is complete, bug free
and up-to-date, we readily accept that
errors may occur. Despite all the care and
precautions we've taken, you may
encounter problems in the documentation.
Please complete this form whenever
you'd like to report errors or suggest
improvements to us.
FAX
Address
Thank you for your kind support.
North America
Hong Kong, Philippines, Oceania
NEC Electronics Inc.
NEC Electronics Hong Kong Ltd.
Corporate Communications Dept. Fax: +852-2886-9022/9044
Fax: 1-800-729-9288
1-408-588-6130
Korea
Europe
NEC Electronics Hong Kong Ltd.
NEC Electronics (Europe) GmbH
Seoul Branch
Technical Documentation Dept.
Fax: 02-528-4411
Fax: +49-211-6503-274
South America
NEC do Brasil S.A.
Fax: +55-11-6462-6829
Asian Nations except Philippines
NEC Electronics Singapore Pte. Ltd.
Fax: +65-250-3583
Japan
NEC Semiconductor Technical Hotline
Fax: 044-435-9608
Taiwan
NEC Electronics Taiwan Ltd.
Fax: 02-2719-5951
I would like to report the following error/make the following suggestion:
Document title:
Document number:
Page number:
If possible, please fax the referenced page or drawing.
Document Rating
Excellent
Good
Acceptable
Poor
Clarity
Technical Accuracy
Organization
CS 00.6