+ 1
1.Can we declare global variables and use it all functions in C ? 2.Can we display a message outside main() in C-language?
6 Réponses
+ 3
William Owens thankyou
+ 2
1. You can declare global variable, however if the variable name is also used in local scope the local scope variable will be used. To declare a global variable declare and initialize prior to main.
//Use Global
#include <stdio.h>
int global_var = 2;
int main(void){
int local_var = 3;
printf("%d\t%d", global_var, local_var);
}
Output: 2 3
//Use Local
#include <stdio.h>
int global_var = 2;
int main(void){
int local_var = 3;
int global_var = 4
printf("%d\t%d", global_var, local_var);
}
output: 4 3
2. I'm not sure what you mean by print a message outside of main but if you create another function or link another file that has a call to a standard out print function you can make a call to it.
+ 2
No it is not necessary to name the variable global I just used that to point out what it was. You can name it anything within the confines of the naming rules of variables.
So it sounds like you are looking at scope.
Yes you can print "outside of main" by scope of the function.
#include <stdio.h>
void print_hi(char* who){
printf("Hello, %s", who);
}
int main(void){
char* name = "William";
print_hi(name);
}
+ 1
I didn't get your 2nd question. What did you mean by "outside main()"? did you mean outside like in another function, or elsewhere like in the global space?
Former is very possible, given the respective function where the message is printed is invoked. The latter, I don't think it will work, or even if it does, may not be a good pattern to follow.
+ 1
William Owens and Ipang
I mean that can we display a message outside int main()?
@William Is it necessary to use global keyword for global variables?
0
Some additional scope of variables:
https://code.sololearn.com/c7q4u3EfwfKu