I have a simple function that I am trying to create. I need this function to add 6 to whatever number the user decides to enter into the program. I have been working with this code for an hour now and cannot figure out what I'm doing wrong, even after looking at multiple examples from the course I am taking. I really appreciate the help.
Here is my code:
#include <stdio.h>
void closing(void);
void addSix(void);
int x;
int result;
int main()
{
int x;
printf("Please enter a number to add to 6: ");
scanf("%d", &x);
getchar();
addSix();
closing();
closing();
return 0;
}
void closing(void)
{
printf("That's all folks.\n");
}
void addSix(void)
{
int result = x+6;
printf("Result: %d\n", result);
}
You've got both a global x variable outside of main(), and a local x inside of main(). The code inside of main() writes to the local x while the code in addSix() reads from the global x.
Remove the int x declaration in main() so that both places access the global x.
You have x declared as both a global variable and variable local to main. When you pass x by pointer to scanf, it refers to the local variable, not the global.
You can remove the local declaration of int x in main but this isn't really the best solution. Generally, global variables should be avoided when possible (though they are, of course, sometimes necessary/the best tool for the job).
The best solution in this case is to make x a parameter to addSix(). There are a few options here:
You can have addSix return the sum and then use that return value
You can pass the address of x to addSix and have the function modify x itself by using a pointer.
The former would look like this:
int addSix(int x) {
return x + 6;
}
The latter would look like this:
void addSix(int * x) {
*x += 6;
}
You have two variables named x. One is a local to main, and the other is a global variable.
The function addSix cannot see the local in main. It can only see the global variable.
You should change addSix so that it is passed the value as a parameter.
void addSix(int x)
{
printf("Result: %d\n", x+6);
}
Call the function like this:
addSix(x);
Or perhaps you want your function to return a value:
int addSix(int x)
{
return x+6;
}
Which you can call like this:
int result = addSix(x);
Both of your global variables are needless. Remove them.
You have a global x, and a local x variable in which you actually save the user input.
Using only the global variable will do the trick for you
#include <stdio.h>
int x;
void addSix(void)
{
int result = x+6;
printf("Result: %d\n", result);
}
int main()
{
printf("Please enter a number to add to 6: ");
scanf("%d", &x);
getchar();
addSix();
return 0;
}
Related
So, if I have the function foo:
float foo(float a, float b){
return a*b;
}
and I call it from another function, how can I call it like this?
void main(){
foo(scanf("%d"), scanf("%d");
}
scanf doesn't return the input string, I don't want to create a bunch of temp variables. Is that possible, and if so how?
You can't directly return a value from scanf. But you can create a function yourself that returns a value from scanf, but it'll still use temp variables inside of it:
int getInteger() {
int input;
scanf("%d", &input);
return input;
}
Then you can use it like:
foo(getInteger(),getInteger());
However, if you really don't wanna use variables, you can just use get_int() from cs50 library. More info here.
#include <cs50.h> // include cs50 to use get_int
int main(void)
{
foo(get_int("Number 1: "),get_int("Number 2:"));
return 0;
}
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 dont have time to explain it deeply, its very simple code but the function always return 'y'(=true)
It is expected to write each number from 1 to squareroot of the generated random number and decide whether it is dividable or not but when i run it, somehow the if statement in the function always return true
#include <stdio.h>
#include <stdlib.h>
int a,b,i;
char c;
char abcd(char c);
int main()
{
srand(time(NULL));
int a=rand()%512;
b=sqrt(a);
i=1;
do{
if(abcd(c)=='y')printf("number %d is dividable by %d\n",a,i);
else printf("number %d is not dividable by %d\n",a,i);
i++;
}while(i<=b);
return 0;
}
char abcd(char c)
{
if(a%i==0)return'y';
else return 'n';
}
When you declare int a inside main as
int a=rand()%512;
you are shadowing your global variable a. The a in main is a different variable that has scope only local to the function main. Therefore, when you are using the value a inside char abcd(char c), this value is the global variable a which is default initialized to 0.
Also, why are you passing a char c variable to function abcd. You aren't using it. Please consider renaming your functions to something that more clearly describes their intent.
You have two different variables a:
one declared at file scope
int a,b,i;
and one declared in main():
int a=rand()%512;
Within its scope (almost all of main()), the latter shadows the former. Elsewhere, such as in function abcd(), only the former is visible. The former is default initialized to 0 and no other value is ever assigned to it, so no matter what value i takes, inside abcd(), the expression a%i evaluates to 0.
This is a good lesson in avoiding file-scope variables. Functions should operate on data accessed directly or indirectly through their parameters, or obtained from an external source. It is poor form for functions to exchange data through file-scope variables. Moreover, it was a red flag to me that your function abcd() declares a parameter that it never uses. Suggested variation:
char abcd(int dividend, int divisor) {
return (dividend % divisor) ? 'n' : 'y';
}
Or even better (because better name and more appropriate return type):
_Bool is_divisible(int dividend, int divisor) {
return !(dividend % divisor);
}
The reason yours doesn't work is because the variable a was declared in a separate scope from the abcd function. The a variable you use inside the abcd function is automatically set to 0, which is why it returns true every time (0 % anything is 0).
When you call abcd, you would need to pass a inside the parameters for it to use the correct value.
But really you don't need the abcd function, you can save a lot of code and directly check if it's divisible. This code should work:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int a, b, i;
char c;
int main()
{
srand(time(NULL));
int a = rand() % 512;
b = sqrt(a);
i = 1;
do {
if (a%i == 0)printf("number %d is dividable by %d\n", a, i);
else printf("number %d is not dividable by %d\n", a, i);
i++;
} while (i <= b);
return 0;
}
I am making a program in C in which I am trying to use the values of local variable in other function. Lets say I have two function foo1 foo2.
int foo1()
{
int a=2,b=3,c;
c=a+b;
return c;
}
int foo2(int c)
{
printf("Value of C is %d",c);
}
is this method correct, if not what else is the way to use values of local variable in other function?
first of all, this two functions foo1() and foo2() are not related...
and local variables have block scope only.
If you want to use them in other functions make them global or use pass by value and pass by reference methods to pass the variables from one function to others...
You cannot, and you should not use local variables from other functions directly.
But in your case you are lucky: the value from foo1() you are interested in is returned to the caller.
This way you can use it as you like:
...
int value = foo1();
foo2(value);
...
or even shorter:
...
foo2(foo1());
...
You can do this -
int foo1()
{
int a=2,b=3,c;
c=a+b;
return c;
}
// c will be passed to the function and printed
int foo2(c)
{
printf("Value of C is %d",c);
}
// get the result of foo1()
int val = foo1();
// call foo2() with the result of foo1()
foo2(val);
One way is to make c variable global so that every function can use it.
other way is to call this returning function in foo2() so that the returned value can be printed.
one way:
int foo1(){
int a=2,int b=3;
int c=a+b;
return c;
}
int foo2(){
printf("value of c = %d",foo1()); //returned value of function foo1() used
}
other way is :
int c=0; //defined global
void foo1()
{
int a=2,int b=3;
c=a+b;
}
void foo2()
{
printf("value of c = %d",c);
}
Here is my code , I want to print 15 and 12 but due to instance member hiding the local value of a is getting printed twice.
#include <stdio.h>
int a = 12;
int main()
{
int a = 15;
printf("Inside a's main local a = : %d\n",a);
printf("In a global a = %d\n",a);
return 0;
}
Why and is there any way to print it in c ? ... BTW I know it in c++.
Use the extern specifier in a new compound statement.
This way:
#include <stdio.h>
int a = 12;
int main(void)
{
int a = 15;
printf("Inside a's main local a = : %d\n", a);
{
extern int a;
printf("In a global a = %d\n", a);
}
return 0;
}
I know this doesn't directly answer your question, but the best way to do this is to change the name of the local variable so it doesn't conflict with the name of the global variable.
If you have control of the code inside the function (i.e., you can add an extern declaration to make the global variable visible), then you can just as easily change the name of the variable.
It's impossible to tell what name would be better. In practice, the variables will undoubtedly have more descriptive names than a. The way they're used should give you some guidance about good names for them.
If they actually serve the same purpose, they probably don't both need to exist. You might remove variable that's local to main(), or, perhaps better, remove the global and pass the local (or its address) to other functions that need to access it.
I think i found my answer in a way... it works
#include <stdio.h>
int a = 5;
int main()
{
int a=10;
if(1)
{
extern int a;
printf("global: %d\n", a);
}
printf("local: %d\n", a);
return 0;
}
add :: for global ambit
#include <stdio.h>
int a=12;
int main()
{
int a=15;
printf("Inside a's main local a = : %d\n",a);
printf("In a global a = %d\n",::a);
return 0;
}