SystemC-n-BehaviorCoding_Fall2021_Section2_C
SystemC-n-BehaviorCoding_Fall2021_Section2_C
Section 2
C Programming Language
The C Book
Dennis M. Ritchie (1941~2011) &
Brian W. Kernighan (1942~, also
the creator of “Hello World”)
Published by Prentice Hall,1988
Unix was developed by Ritchie and
Kenneth L. Thompson (1943~)
# Preprocessor
# is a preprocessor keyword
#define A 100 // to define a keyword
#include “type.h” // to include a user code
// segment
#include <systemc.h> // to include a system
code // segment
#ifdef A // examine a defined
keyword
#else // else to #if
+ 6
#include
Syntax
#include “filename”
#include <filename>
To include a file into the code
Usually to include a header file, i.e. .h file
But you can include another C source code too, or
anything you want
Examples
#include <stdio.h> // search the –L path
#include “src.h” // search current dir
// then the –L path
+ 7
#define
Syntax
#define identifier token-sequence
Token-sequence: a sequence of tokens, i.e. text block
ended by \n (new line)
Example
#define VER 1.0 // a define with value
#define HEADER // a define without value
#define max(A, B) ((A) > (B) ? (A) : (B)) // macro
Example
#if SYSTEM == SYSV
#define HDR “sysv.h”
#elif SYSTEM == BSD
#define HDR “bsd.h”
#elif SYSTEM == MSDOS
#define HDR “msdos.h”
#else
#define HDR “default.h”
#endif
+ 10
#ifdef #ifndef
#ifdefchecks if a keyword is defined
#ifndef checks if a keyword is not defined
Example
#ifdef SYS
#else
#include “sys.h”
#endif
In sys.h:
#ifndef SYS
#define SYS
/* content of sys.h here */
#endif
+ 11
Header file
Source Code
Compilation
Object code
Link
Exp
g++ srca.o srcb.o main.o –o a.out
Compile a library
ar rcs libmylib.a objfile1.o objfile2.o objfile3.o
+ 16
Assignment 1, Problem 1
A hello world code
#include <stdio.h>
int main(int argc, char *argv[]) {
// please add a printf statement before
// the following printf, that prints the
// name of the executable plus ‘says’
// To print a character array, the formatted
// output is
// printf(“%s”, str);
// where str is declared as, say, char str[20];
printf(“Hello World!\n”);
exit(0);
}
For
example, the executable is named run. So,
when run get executed the output becomes:
run says Hello World!
+ 18
Declaration
A Declaration Example
Data Structure
Simply put, data structure is the collection of data
and registers needed in an algorithm
For example, to do bubble sort, one needs an array
to store data, then a temporary register for
swapping two elements
// bubbleSort.h
#ifndef BUBBLE
#define BUBBLE
#endif
+ 21
Data Types
Mathematical
+ binary add, e.g. a = a + b;
+= unary add, e.g. a += b;
- binary subtract, e.g. a = a – b;
-= unary subtract, e.g. a -= b;
* binary multiply, e.g. a = a * b;
*= unary multiply, e.g. a *= b;
/ binary divide, e.g. a = a / b;
/= unary divide, e.g. a /= b
% modula. a % b = the remainder of a divide by b
++ unary increment, e.g a++;
-- unary decrement, e.g. a--;
Logical
&& And, e.g. (a > b) && (b < c)
|| Or, e.g. (a > b) || (b < c)
+ 23
Relational Operators
Bitwise Operators
Function Use
strcat(s,t) Concatenate t to end of s
strncat(s,t,n) Concatenate n characters of t to end of s
strcmp(s,t) Return negative, zero, or positive for
s < t, s == t, or s > t
strncmp(s,t,n) Same as strcmp but only in first n characters
strcpy(s,t) Copy t to s
strncpy(s,t,n) Copy at most n characters of t to s
strlen(s) Return length of s
strchr(s,c) Return pointer to first c in s, or NULL if not present
strrchr(s,c) Return pointer to last c in s, or NULL if not present
+Character Testing and Conversion 26
in <ctype.h>
Function Use
isalpha(c) Non-zero if c is alphabetic, 0 if not
isupper(c) Non-zero if c is upper case, 0 if not
islower(c) Non-zero if c is lower case, 0 if not
isdigit(c) Non-zero if c is digit, 0 if not
isalnum(c) Non-zero if isalpha(c) or isdigit(c), 0 if not
isspace(c) Non-zero if c is blank, tab, newline, return, formfeed,
vertical tab
toupper(c) Return c converted to upper case
tolower(c) Return c converted to lower case
+Statement LHS & RHS, and 27
A simple statement
a = b + c; // Left-Hand-Side (LHS) and
// Right-Hand-Side (RHS)
// RHS is ‘evaluated’ first
// then LHS is ‘updated’
An assignment statement
x = y; // Updates RHS to LHS
// However, RHS is still being
// evaluated first
+ 28
if Statement
if (i > 0)
“i > 0” is an expression. And in this case, a
comparison expression. If the expression is true, then the
code segment controlled by this ‘if’ is executed. If false
then no execution
if (0)
a = b + c; // will this statement be
// executed, ever?
if (1)
x = y * z; // will this statement be
// executed, ever?
if (a = b)
r = s / t; // will this statement be
// executed, ever?
+
? : Expression
equals to
if (expr1)
Example
+ 31
Example
Assignment 1, Problem 2
#include <stdio.h>
int main(int argc, char *argv[]) {
printf(“Hello World!\n”);
// add a loop below to print input arguments,
// if any. Print a space after each input
// argument. When all input arguments are
// printed, print a newline
….
exit(0);
}
A Forever Loop
for ( ; ; )
statement
Is identical to
expr1;
while (expr2) {
statement
expr3;
}
+ 35
do {
statement
} while (expr);
i = 0;
do {
i = i + 1;
} while (i < 10);
+ 36
switch Statement
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}
Example
char c;
switch (c) {
case ‘0’: printf(“0\t”);
break;
case ‘1’: printf(“1\t”);
break;
default: printf(“\n”);
}
+ 37
Pointer
Example:
Function - Introduction
Pass by Value
Pass by Reference 1
Callback Functions
Callback Function in C
#include <stdio.h>
#include <stdlib.h>
/* A possible callback */
int overNineThousand(void) { return (rand() % 1000) + 9001; }
Formatted Output
Formatted Input
int arg1;
float arg2;
scanf(“%d %f\n”, &arg1, &arg2);
+
Input Conversion Specifications
Comprised of a leading % and followed by a conversion
character
Character Input data; Argument type
4
8
+ 49
Escape Sequence
To be used in I/O for formatting control. Always led by a \
File I/O
Example
#include <stdio.h>
FILE *fp1, *fp2;
int arg1;
float arg2;
Section 2-1
Advanced Topics in C
Not “English as
Second Language”
Drag picture to plac
strtok
5
2
+ 53
int main()
{
char str[]=“104.99.34.251";
char *delim = “.";
char * tok;
Execution Result
Breaking string 140.99.34.251 into tokens:
140
99
34
251
+ 55
Assignment 2, Problem 1
Text processing
Open a file (the text file) by command input, e.g. run
TheTextFile
Implement a function to count in the file
How many lines
How many characters
How many upper case letters
How many words
Not “English as
Second Language”
Drag picture to plac
Pointers to Functions
5
6
+ 57
Pointers to Functions
A qsort Example
char *lineptr[MAXLINES];
qsort Discussion
The beginning of
Template
Set up a computing template, that can accept different types
of variables to process, e.g.
void swap(void *[], int, int);
Virtual function
Define a virtual function that dynamically determines which
function to use. However, virtual function is physically
resolved at run time and is better than the qsort example
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
C Files
6
1
+ 62
Files in C
stdin
and stdout are C defined file
descriptors. stdin is the standard input from
the keyboard, and stdout is the standard
output to the monitor
These two are equivalent, in all ways
printf(“I am a good student\n”);
fprintf(stdout, “I am a good student\n”);
sys/select.h
select() allows a program to monitor multiple file descriptors, waiting until one
or more become "ready" for I/O operations (i.e., input, output or exception
throwing that do not block)
Four macros, FD_CLR, FD_ISSET, FD_SET and FD_ZERO are provided to set/test
fd_set, the file descriptor set
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int select(int nfds,
fd_set *readfds, // input FD set
fd_set *writefds, // output FD set
fd_set *exceptfds, // exception FD set
struct timeval *timeout);
void FD_CLR(int fd, fd_set *set); // clear a given FD
int FD_ISSET(int fd, fd_set *set); // test if a FD is set
void FD_SET(int fd, fd_set *set); // set a given FD
void FD_ZERO(fd_set *set); // clear the FD set
+ 65
timeval
#include <sys/time.h>
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
int main(void)
{
fd_set rfds;
struct timeval tv;
int retval;
if (retval == −1)
perror("select()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");
Assignment 2, Problem 2
Pointer exercise
Use void* malloc(size_t size); to allocate argv[1]
bytes of memory, i.e. argv[1] is the second input argument
Use char* and a for loop, assign to the block of memory,
byte-by-byte, ‘A’ to ‘Z’ then ‘1’ to ‘9’ repeatedly, until the
memory runs out
Then use int* and a do-while loop, to print the memory
content, in list of integers. And for each integer accessed,
subtract 1 from it
In the integer process loop, you need to implement a guard
to prevent segmentation fault
+
End of 2nd Section
Thanks to you all!
68