short int PC = 0;
int main() {
foo(&PC) ;
}
void foo(short int PC) {
PC++;
}
How do I successfully update the global variable of PC?
Note: PC must be passed as a parameter and the global variable needs to be modified via the parameter.
As you can tell I am new to C and am trying to understand the difference between * and &. Any help would be much appreciated.
You just need to take the argument as a pointer:
short int PC = 0;
void foo(short int *pc) {
(*pc)++;
}
int main() {
foo(&PC) ;
}
I moved foo() above main() because in C you have to declare things before they are used. If you prefer you could forward declare it by saying void foo(); at the top and leave the definition below.
Related
I have a program, what it does isn't too important, I am mostly curious of the following:
If I have a struct that has pointers to a function, can I pass parameters into the function using that pointer? Here is part of my code
edit: I realized I was a little vague:
So is there anyway to use the variable 'x' of type funcs, to pass parameters into the my_closeit and my_openit using the pointer's initialized by x = {&openit, &closeit}; in the main function? By doing x -> or x. ?
Another Edit:
Would it be x.openit(some pointer, some int); ?
#include<stdio.h>
int my_openit(char* name, int prot);
void my_closeit(void);
typedef struct funcs
{
int (*openit)(char *name, int prot);
void (*closeit)(void);
}funcs;
//I know the first 'funcs' is unnecessary
int main()
{
funcs x = {&my_openit, &my_closeit};
return 0;
}
int my_openit(char* name, int prot)
{
return 0;
}
void my_closeit(void)
{
}
can I pass parameters into the function using that pointer?
Yes, obviously, or it wouldn't be of any use. In your case:
int result = x.openit("something", 123);
Yes, just use function call expression through the pointers:
int r = x.openit("myfile",0);
x.closeit();
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 that If a function has no argument & only return type (say int), then I can change my int variable by assigning the function to my variable as below,
main()
{
int var_name;
var_name = func();
printf("My variable value is updated as : %d", a);
}
func()
{ return 100; }
Also I know that If I have my function's return type as void, with no arguments, then I can only print the value inside the function itself and cannot return anything in turn.
But, my doubt is, is there anything else that I can do to update my var_name by calling a function with no arguments & no return type ?
ie., void func(void); by using something like pointer concepts ??
I could not able to find the exact answer for the same by my searches among so many websites.. I will be very grateful if someone can help me out finding whether I can do it by this way or not,.
Thanks,.
It is possible to modify a local variable in main, from a function with no arguments and no return value, if there's a global pointer to it:
#include <stdio.h>
int *p;
void func() {
*p = 6;
}
int main() {
int a = 5;
p = &a;
func();
printf("a = %d\n", a); // prints: a = 6
return 0;
}
There's no good way to do that. If you want the function to modify a local variable, you should probably change the function so it either returns a value that you can assign to the variable, or takes the variable's address as an argument.
But if you don't mind writing some ugly code, you can define a global (file-scope) pointer variable, assign the local variable's address to the global pointer, and then use that to modify the variable inside the function.
An example:
#include <stdio.h>
int *global_pointer;
void func(void) {
*global_pointer = 42;
}
int main(void) {
int local_variable = 0;
global_pointer = &local_variable;
func();
printf("local_variable = %d\n", local_variable);
}
It's very easy to shoot yourself in the foot his way. For example, if you refer to the pointer after the calling function has terminated (and the local variable no longer exists), you'll have undefined behavior.
This technique can actually be useful if you need to make a quick temporary change in a body of code in which you can't make major interface changes. Just don't do it in code that will be maintained by anyone else -- and wash your hands afterward.
You can have global variable
int var_name;
void func();
int main()
{
func();
printf("%d\n",var_name);
}
void func()
{
var_name = 20;
}
But if your variable is local to main() then this can't be done.
There are two ways to modify the value of var_name.
Make changes in the calling function and return the value.( which you have already shown)
Pass the address of the var_name to the function and have pointer as arguement in the func(int *p) and modify the value inside the func()
Thats it!! No other way this can be done.
I declare in test.h file
extern void test(int *ptr);
extern void myFunc();
extern int num;
I then include the h file in my test1.c file.
I write my functions in test2.c:
void myFunc( )
{
test(&num);
}
void test(int *num )
{
*num = 9;
}
in test1.c I write:
int num = 5;
myFunc();
My question is, how can i use the num variable/pointer in test() without passing it to myFunc()?
The file structure has to stay the same, thats why I am trying to refresh my C on this,
Than you
Check your scope.
void myFunc( )
{
test(&num);
}
This function can't see the variable num unless num is global, and so it's GIGO (garbage in, garbage out).
I know it looks to you like num IS global, but here's the trick:
int num = 5;
myFunc();
I can't see the full code, but because of your formatting I'm guessing that this is using a local copy of num instead of the extern because you're declaring a new variable in local scope inside of the function where you're calling myFunc(). The extern isn't being used.
if int num is global then any function can use it. Second case if you declare int num as local then I think it is an error or you can't access global num inside function where num is already present as local or write your complete code.
This is my code that I am compiling in C. Currently I have a global variable 'code' that is an array of structs(struct instruction). I've been trying to instead make this a local variable in main and pass it as a parameter. Also I believe this means I will need to have read file return a struct instruction*. I would greatly appreciate it if someone could explain, or show me how to properly use 'code' as a local variable. Also I am interested in what makes local variables better or more efficient than global variables. Thanks!
#include<stdio.h>
#include <stdlib.h>
typedef struct instruction{
int op; //opcode
int l; // L
int m; // M
} instr;
FILE * ifp; //input file pointer
FILE * ofp; //output file pointer
instr code[501];
void read_file(instr code[]);
char* lookup_OP(int OP);
void print_program(instr code[]);
void print_input_list(instr code[]);
int main(){
read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
void read_file(instr code[]){
int i = 0;
ifp = fopen("input.txt", "r");
while(!feof(ifp)){
fscanf(ifp,"%d%d%d",&code[i].op, &code[i].l, &code[i].m);
i++;
}
code[i].op = -1; //identifies the end of the code in the array
fclose(ifp);
}
You have to move your declarations inside the functions that need them:
#include <stdio.h>
#include <stdlib.h>
typedef struct instruction{
int op; //opcode
int l; // L
int m; // M
} instr;
void read_file(instr code[]);
char* lookup_OP(int OP);
void print_program(instr code[]);
void print_input_list(instr code[]);
int main(){
instr code[501]; // code[] declaration moved HERE!!!!
read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
void read_file(instr code[]){
int i = 0;
FILE * ifp; //ifp FILE* declaration moved HERE!!!!
ifp = fopen("input.txt", "r");
while(!feof(ifp)){
fscanf(ifp,"%d%d%d",&code[i].op, &code[i].l, &code[i].m);
i++;
}
code[i].op = -1; //identifies the end of the code in the array
fclose(ifp);
}
I've moved ifp declaration inside readfile() and code inside main().
The variable ofp has been removed, because it is not used.
If you are using ofp inside another function, declare it there.
Simple enough.
No real change in efficiency as you have currently coded it.
The only change is the storage for code will be from the stack
int main(){
instr code[501];
read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
I'll go ahead and try to answer the last part of the question:
Also I am interested in what makes local variables better or more
efficient than global variables.
There are a few differences between Local and Global defined variables.
Initialization. Global variables are always initialized to zero, where as local variables will have an unspecified/indeterminate value prior to being assigned. They don't have to be initialized as stated previously.
Scope. Global variables can be accessed by any function in the file (and even out of the file by using extern, without passing a reference to it. So, in your example you didn't need to pass a reference to code to the functions. The functions could have just accessed it normally. Local variables are defined only in the current block.
For example:
int main() {
int j = 0;
{
int i = 0;
printf("%d %d",i,j); /* i and j are visible here */
}
printf("%d %d",i,j); /* only j is visible here */
}
This would not compile, because i is no longer visible in the main code block. Things could get tricky when you have global variables named the same as local variables. It's allowed but not recommended.
Edit: Local variable initialization changes based on comments. Changed text in italics above.