int zipcode; double weight; printf("Enter zip code: "); scanf("%d", &zipcode); printf("Enter weight: "); scanf("%lf", &weight); printf("And now both: "); scanf("%d %lf", &zipcode, &weight);
scanf
.
printf
. The formatting symbols are the same,
except double is %lf
(letter l, letter f).
#include <stdio.h> int main() { double friction, number; int numPeople; // read in some values printf("Enter the amount of friction: "); // prompt stays on line scanf("%lf", &friction ); printf("Enter the number of people:\n"); // prompt goes to next line scanf("%d", &numPeople); number = friction + 3.2 * 2; // This makes no sense printf("The final number was %f\n", number); printf("The value of \"friction\" was %f.\n", friction ); printf("There are %d people here.\n", numPeople); return 0; }
&
in front of the variable’s name tells the
program to use the variable’s address in memory rather than its value.
Address | Value |
---|---|
9278 | 00111011 |
9279 | 00000000 |
9280 | 11111110 |
9281 | 10101010 |
9282 | 01010101 |
9283 | 11110000 |
9284 | 11110000 |
9285 | 11110000 |
9286 | 00010110 |
Memory is divided into many memory locations (or cells).
Each memory cell has a numeric address, which uniquely identifies it.
Every location has a value, whether you put one there or not. The statement “there’s nothing in there” is meaningless.
int i; float f; double d; char c; short int si; long int li; long double ld; // sizeof operator gives the size of a variable printf("char: %zu byte\n", sizeof(c)); printf("short int: %zu bytes\n", sizeof(si)); printf("int: %zu bytes\n", sizeof(i)); printf("long int: %zu bytes\n", sizeof(li)); printf("float: %zu bytes\n", sizeof(f)); printf("double: %zu bytes\n", sizeof(d)); printf("long double: %zu bytes\n", sizeof(ld));
char: 1 byte short int: 2 bytes int: 4 bytes long int: 8 bytes float: 4 bytes double: 8 bytes long double: 16 bytes
But they’re not the same everywhere!
&
to designate we want the address, not the value inside
scanf
needs to know where to store them the values
printf
need the address too?
int x=3; printf("x is now %d\n", x); // No ampersand printf("Gimme: "); scanf("%d", &x); // Ampersand! printf("x is now %d\n", x); // No ampersand
If you use c11 -Wall
, it tells you when you forget the ampersand,
and when you put in an extra one. Use -Wall
!