<< Prev Next >>
Variables
Variables are storage for data. In C, all variables have a data type, which determines their size and their default behaviour. Since we already saw data types on the previous part, let's see what variables offer to us.
(I suggest copy-pasting the code into an editor)
Code: Select all
#include <stdio.h>
// Note the use of "void"
// This means "empty" (or "not defined" on other C contexts)
int main(void)
{
// Declaring 3 variables: a, b and c
// All are signed integers
// ALWAYS ASSIGN INITIAL VALUES FOR YOUR VARIABLES!!
// = is the assignment operator, it gives values for your variables
int a = 3;
int b = 2;
// Value stored in c is b value + a value
int c = a + b;
printf("c = b + a\t%d + %d = %d\n", a, b, c);
printf("\n");
// c is assigned another value. Previous value is lost
c = a - b;
printf("c = b - c\t%d - %d = %d\n", a, b, c);
printf("\n");
// Multiplication
c = a * b;
printf("c = b * c\t%d x %d = %d\n", a, b, c);
printf("\n");
c = a / b;
printf("c = b / c\t%d / %d = %d\n", a, b, c);
printf("\n");
// a + b is computed first, then the value is stored in a
a = a + b;
printf("a = a + b\ta = %d, b = %d\n", a, b);
printf("\n");
// This is the same as the previous one
a += b;
printf("a += b\ta = %d, b = %d\n", a, b);
printf("\n");
// c is assigned value stored on a, then a is incremented by one
c = a++;
printf("c = a++\tc = %d, a = %d\n", c, a);
printf("\n");
// a is incremented by one, then its value is assigned to c
c = ++a;
printf("c = ++a\tc = %d, a = %d\n", c, a);
printf("\n");
// Note operator precedence (which operators are computed first)
c = a++ * b + c;
printf("c = a++ * b + c\ta = %d, b = %d, c = %d\n", a, b, c);
printf("\n");
// Division remainder or module (this arithmetic operator is widely used, learn it well)
c = a % b;
printf("c = a mod b\ta = %d, b = %d, c = %d\n", a, b, c);
printf("\n");
// Bit right shift
b = a >> 3;
printf("b = a >> 3\ta = %d, b = %d, c = %d\n", a, b, c);
printf("b = a >> 3\ta = %08X, b = %08X, c = %08X\n", a, b, c);
printf("\n");
// Bit left shift
c = b << a;
printf("c = b << a\ta = %d, b = %d, c = %d\n", a, b, c);
printf("c = b << a\ta = %08X, b = %08X, c = %08X\n", a, b, c);
printf("\n");
// Binary NOT
c = ~a;
printf("c = ~a\ta = %d, b = %d, c = %d\n", a, b, c);
printf("c = ~a\ta = %08X, b = %08X, c = %08X\n", a, b, c);
// Binary AND
c = a & b;
printf("c = a & b\ta = %d, b = %d, c = %d\n", a, b, c);
printf("c = a & b\ta = %08X, b = %08X, c = %08X\n", a, b, c);
printf("\n");
// Binary OR
c = a | b;
printf("c = a | b\ta = %d, b = %d, c = %d\n", a, b, c);
printf("c = a | b\ta = %08X, b = %08X, c = %08X\n", a, b, c);
printf("\n");
// Binary XOR
c = a ^ b;
printf("c = a ^ b\ta = %d, b = %d, c = %d\n", a, b, c);
printf("c = a ^ b\ta = %08X, b = %08X, c = %08X\n", a, b, c);
printf("\n");
return 0;
}As an additional exercise you might want to guess the values that will be displayed on the screen before running the program.
See on the next part, until then have fun!
<< Prev Next >>






