which prints "lbourne City" instead of the address of letter 'l'.
I do understand that the %s in the printf continues until a null terminator is hit, but not why &s[2] returns a character in the first place.
Thanks.
Name:
Anonymous2013-06-28 13:58
Global variables do exist in C, they're simply declared/defined (and optionally initialized) outside of any function and are accessible via their identifier to any function called in that source file. The 'extern' keyword, as hinted at above, does not define such a variable, it merely declares it (kind of like withe a function prototype versus a function definition); that variable must be defined in another source file which is to be linked.
#include <stdio.h>
void func1(void); //func1 function prototype (i.e. declaration)
void func2(void); //func2 function prototype (i.e. declaration)
int var = 5; //global int variable decl., def. & init.
char arr[] = "foobar"; //global array of char decl., def. & init.
int main(void) //main function (no prototype necessary)
{
printf("\nvar and arr invoked by id from main():\n");
printf("\tvar: %u\n", var);
printf("\tarr: %s\n", arr);
printf("\tsizeof(arr): %u\n", (int)sizeof(arr));
func1(); //call to another function invoking global objects
func2(); //call to yet another function invoking global objects
return(0); //program exit
}
void func1(void) //func1 function definition
{
printf("\nvar and arr invoked by id from func1():\n");
printf("\tvar: %u\n", var);
printf("\tarr: %s\n", arr);
printf("\tsizeof(arr): %u\n", (int)sizeof(arr));
}
void func2(void) //func2 function definition
{
printf("\nvar and arr invoked by id from func2():\n");
printf("\tvar: %u\n", var);
printf("\tarr: %s\n", arr);
printf("\tsizeof(arr): %u\n", (int)sizeof(arr));
}
In the above program, var is a global variable called by id from main() as well as from two other functions; arr is an array seen as such (i.e. not decaying to a mere pointer, as evidenced by its sizeof evaluations) from any of the functions.
Global objects are about as "harmful" as the goto statement - generally not recommended to use on a regular basis, though can be useful in particular situations if used wisely.