You are on page 1of 41

Variables

Fredy Cuenca
Arquitecture of memory
• The memory assigned to a program that is loaded can be divided into
four segments: text (or code), data, stack, and heap.

• The amount of memory allocated for a program is determined by the


architecture set
Arquitecture of memory
• The memory assigned to a program that is loaded into memory can
be divided into 4 segments

Stack

Heap

Data

The text segment or code segment is to allocate the instructions


Code
of the program encoded in machine code
Arquitecture of memory
• The memory assigned to a program that is loaded into memory can
be divided into 4 segments

Stack

Heap

The data segment is to store global and static variables


Data

The text segment or code segment is to allocate the instructions


Code
of the program encoded in machine code
Arquitecture of memory
• The memory assigned to a program that is loaded into memory can
be divided into 4 segments

Stack

The heap is to store dynamically generated variables. This is the only segment that
Heap
can grow at runtime
The data segment is to store global and static variables
Data

The text segment or code segment is to allocate the instructions


Code
of the program encoded in machine code
Arquitecture of memory
• The memory assigned to a program that is loaded into memory can
be divided into 4 segments

Stack The stack segment is to store local variables and information about function calls

The heap is to store dynamically generated variables. This is the only segment that
Heap
can grow at runtime
The data segment is to store global and static variables
Data

The text segment or code segment is to allocate the instructions


Code
of the program encoded in machine code
A first glimpse to C syntax
#include <stdio.h> Directive for importing a header file

int main(void) Header of the main function


{
// printing on the screen comment
printf(“Hello world!”); Body of the main function
return 0;
}
Comments about the program
• Symbols /* and */ to enclose multiline comments, or to use // to
write single-line comments

• Every C program must have at least one function called main

• Every portion of code between braces is called block

• The printf function can be used by including the stdio header


Escape sequences
Escape Description
sequences
\n New line
\b Backspace
\t Horizontal tab
\v Vertical tab
\a Produces a beep
\? Question mark
\” Double quote
\’ Single quote
\\ Backslash \
%% Percentage sign
Variables
• Variables allow storing data

• A variable has a name, a type and a value

• Name variables are sequences of digits, characters, and underscore


characters, that does not begin with a digit. C is case sentitive

• Some commonly used C types are: char, short, int,


long, long long, float, double, long double
Variable assignment
• Variable declaration and variable assignment are two different steps

int a, b; variable declaration


a = 10;
variable assignment
b = a * 2;

• Reading from memory is a nondestructive process. Writing on


memory is a destructive process.
Variables
Variables names correspond to locations in memory

short int number1, number2;

number1 = 4;

number2 = 10*number1;

...
number1 number2
1 byte
Variables

short int number1, number2;

number1 = 4;
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

number2 = 10*number1;

...
number1 number2
1 byte
Variables

short int number1, number2;

number1 = 4;
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

number2 = 10*number1;
0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0

...
number1 number2
1 byte
Printing with format
• The function printf sends formatted output to the screen; it can
carry an arbitrary number of parameters

printf(“My age is %d and my height is %f\n”, age, h);

• Secure C Programming: According to the CERT Secure Coding


Standard, it is a good practice to use puts instead of printf when
you want to display a string terminating with a newline
Format specifiers
Specifier Datatype Example Output
%c character printf(“%c”, ‘a’) A
%d , %i integer print(“%d”, 17) 12
%u unsigned int printf(“%u”, 17u) 17
%o unsigned int (to octal) printf(“%o”, 17) 21
%X unsigned int (to hexadecimal) printf(“%X”, 27) 1B
%f , %F float or double printf(“%f”, 3.14) 3.140000
%ld long integer printf(“%ld”, 3000000) 3000000
%Lf long double printf(“%Lf”, 123.456) 123.456000
%s string printf(“%s”, “Hello”) Hello
%p pointer int a = 1; printf(“%p”, &a) 0064FE00
Integer numbers
Type name # Bytes Range
short int 2 [-32768, 32767]
int 4 [-2147483648, 2147483647]
long int 8 [-9223372036854775808, 9223372036854775807]
long long int 8 [-9223372036854775808, 9223372036854775807]
unsigned short 2 [0, 65535]
unsigned int 4 [0, 4294967295]
unsigned long 8 [0, 18446744073709551615]
unsigned long long 8 [0, 18446744073709551615]
Range limits for integers
Header file: limits.h

Type Lower Limit Upper Limit


short SHRT_MIN SHRT_MAX
int INT_MIN INT_MAX
long LONG_MIN LONG_MAX
long long LLONG_MIN LLONG_MAX
unsigned short 0 USHRT_MAX
unsigned int 0 UINT_MAX
unsigned long 0 ULONG_MAX
unsigned long long 0 ULLONG_MAX
Floating-point numbers

Type name # Bytes Range


float 4 [1.1755e-38, 3.4028e+38] (~8 digits precision)
double 8 [2.2251e-308, 1.7977e+308] (~16 digits precision)
long double 16 [2.1220e-314, 2.1220e-314] (~20 digits precision)
Range limits for floating-point numbers
Header file: float.h

Type Lower Limit Upper Limit


float FLT_MIN FLT_MAX
double DBL_MIN DBL_MAX
long double LDBL_MIN LDBL_MAX
About integer constants
• Integer constants may be accompanied by one of the following
suffixes: L, LL, U, UL, ULL. The abscence of a suffix indicates
that the constant is an integer

int x = 100;
long y = 2094L;
unsigned int z = 34U;
About floating-point constants
• Float numbers may have a suffix: f or L. The abscence of a suffice
indicates that the constant is double
• When you use exponential notation (with e or E) the constant is
considered a floating point number

float weight = 72.5f;


double salary = 4387.54;
long double a = 99312432.54L

float x = 3E4;
float y = 12e-4f;
Controlling the output field width
• Floating-point numbers can be formatted as follows:
%[width][.precision][modifier]f

• width defines the number of spaces to be used to print the output


• precision defines the number of decimal places to be printed
• modifier may be L if the value to be printed is double

• By default, values are right-aligned. A minus sign (–) right after the
symbol % will print left-aligned data.
Arithmetic operators
Operator Operations Order of evaluation (Precedence)
() Parentheses Evaluated first. If the parentheses are nested, the innermost expression is
evaluated first. If there are several pairs of parentheses on the same level,
they’re evaluated left to right

* Multiplication
/ Division Evaluated second. If there are several, they’re evaluated left to right
Remainder
%
+ Addition Evaluated third. If there are several, they’re evaluated left to right
- Substraction

= Assignment Evaluated last.


Implicit type conversion
• When the operands of an arithmetic operation have different data
types, the compiler arranges for the value that is of a type with a
more limited range to be converted to the type of the other variable.

• When the value of an expression on the right side of an assignment


operator (=) is a different type to the variable on the left, the value of
the expression will be transformed.
• This may cause lost of information, since data may be truncated
• In such cases, the compiler should throw a warning message (you may need
to use gcc –Wconversion <myFile.c>
A basic example of implicit conversion
• Compile the following code snippets with the option gcc -Wconversion

float d = 10 / 3; float d = 10 / 3.0;


printf("%f", d) printf("%f", d)

float d = 10 / 3.0f;
printf("%f", d)
Explicit type conversión (casting)

• A variable myVar that wants to be tranformed into a different type


must be expressed as: (<new-data-type>)myVar

float d = (float)10.0 / 3.0; float d = (float) (10.0 / 3.0);


printf("%f", d); printf("%f", d);
Characters
• Characters can be stored in variables of type char

• Character constants are written between single-quotes

• Characters have a dual representation:


• Can be printed as characters, by using the specifier %c
• Can be printed as integers, by using the specifier %d
Equality and relational operators
• All relational operators have the same precedence and associate left to right
• The equality operator has a lower level of precedence than relational operators

Operator Operations
== equal to
Equality
operators not equal to
!=
> is greater than

< is less than


Relational
operators >= is greater than or equal to

<= is less than or equal to


Precedence of all operators studied so far
Operator Associativity
() left to right

*/% left to right

+- left to right

< > <= >= left to right


level of
== != left to right precedence
= left to right
Booleans
• Booleans can be stored in variables of type bool, which is defined in
the header file stdbool.h

• Boolean variables can be assigned with the constants true or


false, or with expressions involving relational and equality
operators (a.k.a. boolean expressions)

• The format specifier for booleans is %d. A number 1 will be printed


when the value is true, or 0, otherwise. In general, C considers 0 as
false and any non-zero value as positive.
Booleans
• Comparisons between floating-point numbers may consider that the
exact representation of many of these numbers cannot be stored in a
finite amount of memory.

• The variable bool r =(1.0 == 1.0f) will be evaluated to false

• It is common to use an epsilon to ignore differences due to inexact


representation.
The op= operator
Assignment expressions like

<myVar> = <myVar> + <something>;

can be shorten as follows

<myVar> += <something>;

The same is true for operands: +, - , * , / , %


Increment and decrement operator
• Both are unary operators
• Both can be used as a preffix or suffix

++a Increment a by 1, then use the new value of a in the expression in which a resides

a++ Use the current value of a in the expression in which a resides, then increment a by 1

--b Decrement b by 1, then use the new value of b in the expression in which b resides

b-- Use the current value of b in the expression in which b resides, then decrement b by 1
Reading user’s input
The function scanf (library stdio.h) reads data from the keyboard.

Syntax:
address operator
format control string variable name

scanf("%d", &age)
Characters

char answer = 'Y';


The getchar() is meant to consume

while(answer == 'Y') the <ENTER> after the user’s input

{
puts("Do you want to continue?");
scanf("%c", &answer);
getchar();
}
Constants
• Constants are declared as follows:

const <data-type> <constant-name> = <value> ;

• The compiler will check that constants values are not modified
throughout the program
Enumerations
Enumerations allow defining a new data type with a small range of values

Syntax:

enum [dataTypeName] { <list of values separated by commas> }


Enumerations
Enumerators are considered integer values starting from zero

enum score {Terrible, Bad, Average, Good, Excellent};

/* myRanking and yourRanking can only take 1 out of 5 values */


enum score myRanking = Good;
enum score yourRanking = Bad;

float avg = (myRanking + yourRanking) / 2.0;

printf("The average ranking is: %.2f\n", avg); // 2.0


Enumerations
• One can force enumerators to start with a non-zero value
enum score {Terrible=-2, Bad, Average, Good, Excellent};

• One can assign a value for each enumerator

enum score {Terrible=-1, Bad=2, Average=5, Good=9, Excellent=20};


Mathematical functions (math.h)

floor(x) Returns the largest integer that isn’t greater than x as type double
ceil(x) Returns the smallest integer that isn’t less than x as type double
fabs(x) Returns the absolute value of x
log(x) Returns the natural logarithm (base e) of x
log10(x) Returns the logarithm to base 10 of x
exp(x) Returns e^x
sqrt(x) Returns the sqare root of x
pow(x, y) Returns x^y

You might also like