# include <stdio.h>
int x = 5;
int main(void)
{
int x = 7;
printf("output = %d\n", x);
}
The above program shows output as 7.
How to print 5 in c?
thanx...
So you're asking how to access a global that's shadowed by a local? You can't in that scope, but something like this should work
# include <stdio.h>
int x = 5;
int get_global_x()
{
return x;
}
int main(void)
{
int x = 7;
printf("output = %d\n", get_global_x());
}
Don't redeclare the x variable in the main function...
In fact, i'm sensing (perhaprs wrongly) that there's another question behind your code, but i'll keep my reaction to it short: if you want to mix global variables and local variables, try to have a convention to distinguish them; for example globals in ALL_CAPS to shout out its scope :)
EDIT: By the way, you should be getting at least a warning from your compiler for redefining a different scope/same name variable. it's really not recommended doing that. Try to always aim for minimum warnings...
You need to give your two variables meaningful names. I'm sure you aren't using x in your real code so do the two vars actually have the same meaning and therefore the same name? If so you could at least do (assuming your ints are counts, but works for all other purposes):
int global_countOfThings = 5;
int main(void)
{
int countOfThings = 7;
printf("output = %d\n", global_countOfThings );
}
But hopefully you'll be able to do something like:
int countOfDucks = 5;
int main(void)
{
int countOfGeese = 7;
printf("output = %d\n", countOfDucks );
}
And of course if you can some how change your code to not use globals you'll be better off in the long run.
You are declaring the same variable in global and local scope. If the same variable is declared in global and local scope, the variable will be treated as local variable. That's the reason you are getting the answer as 7.
Delete the x = 7 line, move the print statement before you print the value or set a different variable to 7 (i.e. write y = 7 instead of x = 7).
u have already declared x to behave as if it is a global variable.to print 5 u can write the pritf statement as:
printf("%d\n",x-2);
The above would print 5.
If you want it 5, why you assign 7? :-) Or you want to access global variable with the same name as local one? Then you might use namespaces... Not sure about C :-)
Related
I had this assignment at school, wherein I had to find the output of the following C code, and also, to explain the output.
#include<stdio.h>
int i;
void fun1(void);
void fun2(void);
int main()
{
fun1();
fun2();
return 0;
}
void fun1(){
i=20;
printf("%d\t",i);
}
void fun2(){
int i=50;
printf("%d",i);
}
The output is 20 50
Because in fun1() the Global Variable 'i' is assigned to 20 and printed. And in fun2() the variable 'i' is a Local Variable, which is declared and initialized to 50, which is then printed.
I have this following question out of curiosity, how do I use the global variable 'i', in fun2()?
A simple solution would be to simply change the name and avoid the whole thing. But my curiosity is due to Java, where there is a keyword "this" to access class variable instead of a local variable.
so is there any way to do that in C?
The only way is to hide the declaration of the local variable in a code block.
For example
#include <stdio.h>
int i = 10;
void fun2( void )
{
int i = 20;
printf("local i = %d\n",i);
{
extern int i;
printf( "global i = %d\n",i);
}
}
int main(void)
{
fun2();
}
The program output is
local i = 20
global i = 10
There is no way to access a global parameter inside a function that has a local variable with the same name. It is usually bad practice to create such local variables in C though, as you saw, it is not prohibited.
In C++ you can solve it using namespaces but there is no equivalent in C.
The best way is to pass parameters to the function
void fun2(int fromExternalWorld){
int i=50;
printf("%d ",fromExternalWorld);
printf("%d\n",i);
}
int main(void)
{
fun2(i);
}
Otherwise is not possible to have two symbols with same name visible in the same scope.
You could cheat and create a pointer to the global i before declaring the local i:
void fun2( void )
{
int *ip = &i; // get address of global i
int i = 50; // local i ”shadows" global i
printf( "local i = %d, global i = %d\n", i, *ip );
}
EDIT
Seeing as this answer got accepted, I must emphasize that you should never write code like this. This is a band-aid around poor programming practice.
Avoid globals where possible, and where not possible use a naming convention that clearly marks them as global and is unlikely to be shadowed (such as prefixing with a g_ or something similar).
I can't tell you how many hours I've wasted chasing down issues that were due to a naming collision like this.
I know there must be a duplicate, but I didn't find anything. In C, I see a lot of code examples where the authors only assign values after the declaration of the variable, is there a good reason for doing that?
int main(void)
{
int x; // declare "x"
x = 5; // assign 5 to "x"
return 66;
}
And what's the different between that and just declaring and assigning a value in one line?
int main(void)
{
int x = 5; // declare "x" and assign in the same line
return 66;
}
It's mostly a matter of style these days. In many cases it's less error prone to assign a value to a variable at the point where it's first used, and perhaps as close to its point of first use as possible.
On the other hand, I've certainly seen cases where an algorithm is easier to follow when it isn't dotted with statements that introduce new variables. Collecting up all these statements before the main body of the algorithm may allow the algorithm itself to fit on a single page/screen.
And it seems pointless to assign an initial value to a variable in a construction like this:
int foo;
if (bar == 42)
foo = 1;
else
foo = -1;
Here's an example regarding local and global variables. The result of this program displays the value of the global variable g.
What if I want to print/use the value of the global variable?
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf("value of g = %d\n", g);
return 0;
}
Use a pointer to the global variable
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
int *pg = &g;
/* local variable declaration */
int g = 10;
printf("value of g = %d\n", *pg);
return 0;
}
This is not possible, the local g shadows the global one. However, in practice this is more a feature than a limitation since it means you don't have to worry about choosing variable names distinct from globals, and, of course, you can easily control your local names to allow access to a like-named global.
The scope of the variable int g=10; is just within main() so you can print the global variable anywhere apart from main() like calling some API as shown below.Else if you want to print it within main() then you need to have a pointer to your global variable and dereference it to get the value. The below approach doesn't introduce any new variable .
#include <stdio.h>
/* global variable declaration */
int g = 20;
void print_global()
{
printf("value of g = %d\n", g);
}
int main ()
{
/* local variable declaration */
int g = 10;
printf("value of g = %d\n", g);
print_global();
return 0;
}
Only for globals, you can just call another function to access it (and maybe return a pointer).
For all cases of shadowing, you can use a pointer you saved earlier.
Still, the best option is the simplest one: Just change the identifier in the inner scope to avoid shadowing.
Delete the local variable and declare it as global... Since the global variable has scope throughout the program, you can use it in any function of the program. But if you still want to declare the same variable locally then the local variable dominates the variable declared globally.
I have declared int x in file one and by mistake I declared another variable of type char with the same name x in file two, and I wait the compiler or the linker to give me an error, but there are no errors displayed. and when I use the debugger I see that int x is converted to char x , is that true?! and what actually happens here?!
Show this modification on my code:
File One
#include <stdio.h>
int x = 50; /** declare global variable called
x **/
int main()
{
print();
printf(" global in file one = %d",x); /** Modification is just here **/
return 0;
}
File Two
char x;
void print(void)
{
x = 100;
printf("global in file two = %d ",x);
return;
}
My expected results are = global in file two = 100 global in file one = 50
but The results are : global in file two = 100 global in file one = 100
When I use the debugger I see that int x is converted to char x , is that true?! and what actually happens here?
You're in troublesome territory here. Technically your program causes undefined behaviour. char x is a tentative definition, since it doesn't have an initializer. That means the linker unifies it with the int x in the other file at link time. It's a bit weird looking, since your two declarations have different types, but it appears to have successfully linked in your case. Anyway, you have only one x, and luck is making it work the way you're seeing it (and little-endian architecture, probably).
If you want the two variables to be independent, make them static, and they'll be restricted to the scope of their respective translation units.
I want to use the same variable name with a different datatype in C program without casting.
I really wanna do that don't ask why.
So how can I do that ?
And how can I handle the error if this variable doesn't exist while doing prophylactic unsetting ?
You can't. The closest you can get is creating separate scopes and using the same variable name in them:
{
int val;
// do something with 'val'
}
{
double val;
// do something with 'val'
}
If you want the same memory to be referenced with two different types, use a union. Otherwise, know that what follows is a terrible idea.
int foo;
float bar;
#define MY_NAME foo
// use MY_NAME as an int.
#undef MY_NAME
#define MY_NAME bar
// use MY_NAME as a float.
I don't believe this is possible in C. The only way I can imagine doing this would be to write your program such that the two different variables exist in completely different scopes. Such as when you use them in different functions. Other than that, you're stuck with your first variable, pick a different name.
My suggestion -- if you absolutely require then to exist in the same scope -- would be to prefix the name with a type identifying letter, so:
int iVal;
double dVal;
When you define a variable with a name that already exists, the new definition "hides" the old one.
#include <stdio.h>
int main(void) {
int variable = 42;
printf("variable is an int and its value is %d\n", variable);
{
double variable = -0.000000000000003;
printf("variable is a double and its value is %g\n", variable);
}
{
FILE *variable = NULL;
printf("variable is a FILE * and its value is NULL :-)\n");
}
printf("variable is an int again and its value is, again, %d\n", variable);
return 0;
}
You can't change the type of a variable in C. You can use a little preprocessor trickery to get the illusion of what you want. i.e.
int myvar = 10;
// code using myvar as an int
#define myvar _myvar
char *myvar = "...";
// code using myvar as a char*
That being said, I cannot discourage this strongly enough. Don't do it!