Title: C Programming Basics
1C Programming Series
Basics for High-Performance Computing Yaakoub Y.
El Khamra
2Agenda
- Background
- What we will cover
- Why learn C
- When to use C
- The C programming language
- Data types
- Operations
- Control flow
- Advanced C topics
- pointers
- IO, File IO
- System calls
- Signals
- HPC and C
- Notes on Style
- Editors, tools, good practice
- Where to go from here
3What we will cover
- Introductory session, we cover the basics
- data types, arrays, control statements and
functions - paradigms, good practice, writing efficient code
- IDE's, multicore/parallel programming tools
4Why learn C
- Been around for over 30 years (lots of code to
learn from, plenty more to use) - programming language of the Unix OS
- Higher level than assembly and fortran 77, lower
level than C - C compilers are on all architectures, from
supercomputers to PIC MCU's - It is a common language when all the team knows C
it is a good idea to develop the project in C - It is good to understand the C programming
language design
5When to use/not use C?
- Most libraries have C interfaces
- It is easy to make system calls on nix platform
- For string manipulation, C lacks a lot of useful
tools - For programs requiring a lot of abstraction use
something more high level - When you need to use a template, go ahead and use
C, C has no templates
6Agenda
- Background
- What we will cover
- Why learn C
- When to use C
- The C programming language
- Data types
- Operations
- Control flow
- Advanced C topics
- pointers
- IO, File IO
- System calls
- Signals
- HPC and C
- Notes on Style
- Editors, tools, good practice
- Where to go from here
7But first HelloWorld.c
8Data Types
- All variables must be defined in C.
- data types define variables before they are used
- The definition of a variable will assign storage
for the variable and define the type of data that
will be held in the location - Has the form
- typename variablename
- Examples
- int myInteger
- char myCharacter
9Integer Types
- Byte sizes for Lonestar Ranger.
- How to get the sizes
- char c
- int i
- printf("d,d\n", sizeof (c),
- sizeof (i) )
- Output 1,4
- Common sizes (in bytes)
10Float Types
- The majority of scientific codes will use
floating-point data in double precision - float (single precision) 4 bytes
- double - 8 bytes
11Character Types
- char myName10
- Create a string variable called "myName" which
contains 10 elements - strcpy(myName, "Evan")
- myName"yye00" /Invalid syntax/
12Assigning Values
- Why can't I assign a string to a value?
- Only scalar (a single value) can be assigned at a
time. A string is an array of values, and each
location must be assigned individually - Values are assigned by the assignment operator
"". - Valid syntax
- char myChar
- int x
- x 3
- myChar x'
- notice the use of single quotes (') instead of
double quotes - ("), because it is a single character, not a
string.
13Mathematical Operations
- mathematical operations , -, multiply ,
divide / - increment decrement , --
- result
- result result 1
- capture a remainder for integer numbers
- result sum 4 /result is 2/
- when an operation occurs on variables of
different type, the lesser type is promoted (it
may be necessary to typecast)
14Program Flow
- Loops
- for(i 0 i lt num i) ...
- while(thisValueIsTrue) ...
- Do ...
- ....while(thisValueisTrue)
- Conditionals (nested if else statements are
possible) - if (valueIsTrue) do this..
- else if (AnotherValueIsTrue)do that..
- else do this other thing..
-
15Switch Statements
- Useful for constructing argument parsing instead
of using large if-else-if-else statements - switch(letter)
-
- case 'A' printf("A, for apple\n")
- break
- case 'B' printf("B, for Bob Garza\n")
- break
-
-
16Constructing Logic
- Use in conditional statements (and loops)
- Relational operators ( lt, gt, lt, gt )
Equality operators ( , ! ) - if (value1 gt value2)
- Logical operators "" (and), "" (or), "!"
(not) - if (value1 gt value2 value3)
- Order of evaluation
- depending on the operator precedence is not a
good idea in any language, use parenthesis - if((value1 gt value2) value3)
17Advanced Control
- continue
- used in a for() loop will cause the current
iteration to stop and will start the next loop
iteration - break
- used to "break" outside of a loop or conditional
prematurely. - exit
- quits the program (please make sure you have only
one exit point to your code)
18Operator Precedence
- -- Postfix increment and decrement
- () Function call
- Array subscribing
- -- Prefix increment and decrement
- / Multiplication, division, and
modulus (remainder) - - Addition and subtraction
- lt lt Relational less than and less than
or equal to - gt gt Relational greater than and
greater than or equal to - Logical AND
- Logical OR
19Agenda
- Background
- What we will cover
- Why learn C
- When to use C
- The C programming language
- Data types
- Operations
- Control flow
- Advanced C topics
- pointers
- IO, File IO
- System calls
- Signals
- HPC and C
- Notes on Style
- Editors, tools, good practice
- Where to go from here
20Pointers
- Elusive, tricky and hard to master
- Very easy to misuse pointers, this typically
leads to - Segmentation faults
- Memory access issues (memory stomping), memory
corruption, possibly unintended, erratic behavior
in the code - Memory leaks
- We include them in this introduction to C because
they are essential to efficient code
21What is a pointer
- A pointer is a data type whose value refers
directly to another value stored in memory using
its address - A pointer references a value in memory, and to
retrieve the value is to dereference a pointer - Pointers to different data types have different
types, example - int intPtr /pointer to integer/
- double doublePtr /pointer to double/
22Pointer Example
- What would the output be in this case?
23IO
- printf, the all-in-one output function for C.
- printf ("hello world\n")
- Output hello world
-
- char myName10yye00
- printf("my name is s \n", myName)
- Output my name is yye00
24Conversion Characters
- Printing values of all data types is possible
with conversion characters. Each conversion
character tells printf what kind of data is
expected to follow. - Common Characters
- d, i, u integer
- x hexadecimal
- f floating point number
- s string
- c character
25More printf Examples
- printf("My name is s and I am d yrs old\n",
- myName, myAge)
- Carriage control is provided by the backslash
- \n, newline
- \t tab
- \b backspace
- \\ produce a single backslash "\"
26Advanced Output
- printf() is a highly robust function that can
parse output effectively - printf("\n\nHOST\t\tR15s\tR1m\tR15m\tPA
GES\t\tMEM\tSWAP\tTEMP\n") - printf("s\t5.1f\t5.1f\t5.1f\t5.1fP/s\t4.fM\t
4.fM\t4.fM\n", hostsi.hostName,hostsi.liR15S
,hostsi.liR1M,hostsi.liR15M,hostsi.liP
G,hostsi.liMEM,hostsi.liSWP,hostsi.liT
MP) - Output
- HOST R15s R1m R15m PAGES
MEM SWAP TEMP - c21-208 1.0 1.0 1.0 2.1P/s
6468M 2021M 55776M
27Input
- Input can be handled with the scanf function
which behaves similarly to printf - int MyInteger
- float MyFloat
- scanf ("d f", MyInteger, MyFloat)
- Variables must be handed to scanf with the
address operator "". In C the address operator
gives a variable's address in memory, (a
pointer), not the value itself.
28Working with scanf
- scanf will parse standard input and match cases
that it finds. - gets (string)
- grabs all of the string input on the screen and
will save it in the array string - Later in the presentation we will see a better
way to do input processing
29Working with Files
- STDIN and STDOUT are streams (for input and
output) - Files are also streams, have similar functions
to scanf and printf - / definitions /
- define NAMELIMIT 40
- FILE fptr
- char filenameNAMELIMIT
- / in code /
- fptr fopen(filename, "r")
- if ( fptr NULL)
- perror("error opening file")
-
- fclose (fptr)
30Working with File Pointers
- File pointers can be manipulated in the same
fashion as I/O from the keyboard and to the
screen. - Example fscanf reads input from the file pointer
- int item
- fscanf (fptr, "d", item) / read /
- printf( "d\n", item) / print /
31fprintf() and fscanf()
- Usage is exactly the same as printf and
scanfexcept specify file pointer - fprintf(fptr, " .")
- Incidentally, all input and output are file
pointers that can be manipulated. STDOUT is the
screen pointer. (STDIN is the input pointer) - fprintf(STDOUT, "Hi there!")
- printf("Hi there!") /equivalent
statement/
32fopen() arguments
FILE fptr fptr fopen( "myfile",
"r") - Open file for reading
33Putting I/O together
According to the MAN page for gets() BUGS
Never use getS(). Because it is impossible to
tell without knowing the data in advance how
many characters gets() will read, and
because gets() will continue to store
characters past the end of the buffer, it is
extremely dangerous to use. It has been used to
break computer security. Use fgets() instead
34System Calls
system() Call a UNIX system program
externally example system(clear) / clears
the screen / system(command) is equivalent
to /bin/sh -c command System calls are expensive
computationally. Most system calls can be
accomplished by a similar C library function
chmod, chdir,rename (see section 2 and 3 or 3p
man pages)
35Retrieving Environment Variables
include ltstdio.hgt include ltstdlib.hgt / To
shorten example, not using argp / int main (int
argc, char argv, char envp) char home,
host home getenv("HOME") host
getenv("HOSTNAME") printf ("Your home
directory is s on s.\n", home, host) return
0
36Signals
- Programs are given signals by the UNIX system to
quit or exit, and they also create signals when
errors occur - It is useful to be able to "catch" signals in
order to execute actions when bugs occur - extremely advanced programming methods (read the
manual before attempting this)
37Continuing after Signals
- Sample code (modified) to illustrate catching an
interrupt signal - Code will run indefinitely and when we hit Ctrl-C
it will go to the handler function
38Power of Signals
- "Graceful" exits when things go wrong
- Program receives a kill signal while files are
open - print useful information such as an error code
- point fault locations such as functions or
procedures
39Agenda
- Background
- What we will cover
- Why learn C
- When to use C
- The C programming language
- Data types
- Operations
- Control flow
- Advanced C topics
- pointers
- IO, File IO
- System calls
- Signals
- HPC and C
- Notes on Style
- Editors, tools, good practice
- Where to go from here
40HPC and C
- C is a lingua franca amongst HPC packages
- Most HPC libraries have C interfaces to their
functions - Typically, for in-house parallel code, you will
use either OpenMP or MPI, rarely anything else - OpenMP and MPI can be used in C effectively, a
lot of MPI implementations are in fact written in
C
41HPC and C
- Before jumping into OpenMP and MPI, understand
the problem you are trying to solve and the
parallelism model - Chances are somebody already wrote a library to
solve a lot of the problems you encounter, (reuse
reuse reuse) - Eventually, you will need to learn OpenMP or MPI
- TACC hosts OpenMP and MPI tutorials on a regular
basis
42MPI Code
43OpenMPCode
44Agenda
- Background
- What we will cover
- Why learn C
- When to use C
- The C programming language
- Data types
- Operations
- Control flow
- Advanced C topics
- pointers
- IO, File IO
- System calls
- Signals
- HPC and C
- Notes on Style
- Editors, tools, good practice
- Where to go from here
45Sadly, this is valid C code
46Code Style
- Give your variables useful, meaningful names
whenever possible, iterators and temp values can
be excluded - Give your functions meaningful names func is
not a good name, and chances are other
programmers already use func in their code and
that will cause conflicts - Be consistent pick a style and stick to it
- Do not be hesitant to add comments, but when you
add them, make sure they actually say something
useful / here we do this / is quite silly to
add in code
47Code Style
- If you have more than one version of your code,
time to move to a version control system (check
TACC tutorials page for more info) - When you have to type more than five words to
compile your code, time to use a make or a build
system - When you have a file that is over 1k lines, time
to break it down into many smaller more
manageable files - When your main function is over 200 lines of code
long, time to read more about functions and start
using them. If you know a software engineer, ask
them about design patterns - And finally, and most importantly, read your own
code before you show it to others, and make sure
you do show it to others for them to read. Code
reviews save you time, effort and frustration
48Different Styles
- GNU Style (my personal preference)
49Variable/Function naming
- We used to have the Hungarian Notation, do not
use aforementioned notation! - Matter of preference but keep names short and
meaningful use underscores and capitalization
this_is_a_variable or ThisIsAVariable - Make sure variable names are not misleading, if
it does not confuse you it will confuse somebody
else - When in doubt something is not sufficiently
clear, add more documentation
50Agenda
- Background
- What we will cover
- Why learn C
- When to use C
- The C programming language
- Data types
- Operations
- Control flow
- Advanced C topics
- pointers
- IO, File IO
- System calls
- Signals
- HPC and C
- Notes on Style
- Editors, tools, good practice
- Where to go from here
51Advanced Editors
- Vi/Vim is good, ubiquitous, easy to use but not
terribly productive - While you can add plugins to vi/vim such as
tabby, you cannot browse the code structure - This lead to the rise of integrated development
environments (emacs does not count) - Most of IDE's are a personal choice, you have to
use the tools that you are comfortable with and
provide the features you require
52Advanced Editors (cont)
- On Linux
- Eclipse, Geany, Kdevelop, Nedit, Scite
- On Windows
- Eclipse, Scite, UltraEdit32, MS Developer Studio
- On Mac
- Eclipse, Scite, Xcode
- Many more IDE's exist, but the IDE I use is
Eclipse
53Code Tools
- indent indents your code and makes it look
pretty - splint, uno, cppcheck statically check C
programs for security vulnerabilities and common
programming mistakes - gdb debug your code
- ddd debug your code with a nice graphical
interface - valgrind Memory checker for your code
54Good Practice
- Exactly that, practice write sort algorithms
repeatedly, think of them as Katas - Read your own code, and have others read it too
- Write code in teams one man on keyboard another
looking over the shoulder (Agile Code
development) - Read good references mythical man month,
practical C programming, write great code
55Agenda
- Background
- What we will cover
- Why learn C
- When to use C
- The C programming language
- Data types
- Operations
- Control flow
- Advanced C topics
- pointers
- IO, File IO
- System calls
- Signals
- HPC and C
- Notes on Style
- Editors, tools, good practice
- Where to go from here
56Where to go from here
- The C programming language by Kernighan and
Ritchie (aka the C bible) - Practical C Programming by Steve Oualline
- Write Great Code book series
- http//www.ioccc.org/
- Tune in to more tutorials at TACC for everything
from development, using the various HPC packages
(everything from PDEs, linear algebra, comp.
Chemistry etc...) to debugging, profiling,
optimization and visualization