Week4-misc - External and static variables External...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
1 External and static variables • External variable : declared outside the body of a function • File scope : visible from the point of the declaration to the end of the file. • Static storage duration : through the duration of the program. • External/global variables have file scope and static storage duration.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 static variables static int i; void f(void) { static int j; } static used outside a block means that the variable is only visible in the file in which it is declared static used in a block means that the variable lives beyond the duration of the block, and is initialized only once.
Background image of page 2
3 Example #include <stdio.h> int nextvalue() { static int i = 0; i++; return i; } int main() { int i; for(i = 10; i > 0; i--) { printf("%d\n", nextvalue() ); } return 0; } output: 1 2 3 4 5 6 7 8 9 10
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4 extern • informs the compiler that i is an int variable, but doesn't cause it to allocate space. filea.c fileb.c extern int i; void f(void) { i++; } int i = 0; extern void f(void); void g(void) { f(); printf("%d\n", i); }
Background image of page 4
5 typedef • You can define new types using typedef . • You have already seen the effects of typedef typedef unsigned int size_t; • Example struct personrec { char name[20]; int age; }; typedef struct personrec Person; Person *p = malloc(sizeof(Person));
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
6 typedef • You can define new types using typedef . • You have already seen the effects of typedef typedef unsigned int size_t; • Example typedef struct { char name[20]; int age; } Person; Person *p = malloc(sizeof(Person));
Background image of page 6
7 Header files
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 8
This is the end of the preview. Sign up to access the rest of the document.

This document was uploaded on 08/02/2011.

Page1 / 23

Week4-misc - External and static variables External...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online