Home > Net >  c variables not visible to main. using C header files
c variables not visible to main. using C header files

Time:11-13

I am trying to define variables in a C header file. Then do work on these variables in a function and use the new values of these variables in the main function. the code looks as follows: C header :


#ifndef _myheader_h
#define _myheader_h
extern int a;
extern int b;
void get_q (int, int, char*);
#endif

my c source file looks like this:

#include <stdlib.h>
#include <stdio.h>
#include "myheader.h"
#include <string.h>

int a;
int b;

void get_q (int a, int b, char* q){
    if(strstr(q, "somestring1")!=NULL){
        a=1;
        b=0;
        printf("a was chosen \n");
        printf( " a= %i, b= %i \n", a, b);
        return;
    }else if (strstr(q, "somestring2")!=NULL){
        printf("b was chosen \n");
        a=0;
        b=1;
        return;
    }else {
        printf("please enter a valid q");
        return;
    }


}
int main (int argc, char **argv){
    get_q(a, b, argv[1]);
    printf( " a = %i , b = %i \n ", a, b);
    if(a){
        //some function 

    }else if (b){
        // some function
    }else {
        printf("no valid q was given");
    }
}

now the problem is when I enter "somestring1" the output is:

//from function get_q

a was chosen

a =1 , b=0

//from main

a=0, b=0

no valid q was given

if I declared int a=0; int b=0; inside the main function. the same error happens what am I missing here and why are the variables not visible to the main ?

CodePudding user response:

void get_q (int a, int b, char* q) declares get_q to have parameters named a and b (and q). Those are different variables from the external a and b, and they hide the external a and b. If you want to use the external a and b, get_q must not have parameters with those names.

(Note that using non-constant external variables is generally bad design in a program with limited exceptions.)

CodePudding user response:

The function get_q

void get_q (int a, int b, char* q){

deals with copies of values of the values of the variables a and b declared in the file scope.

get_q(a, b, argv[1]);

So changing the copies within the function does not result in changing the original values of the variables a and b.

You could declare the function like

void get_q ( char* q){

and call it like

get_q(argv[1]);

But in general it is a bad idea to define functions that depend on global variables.

You could declare the variables a and b in main and pass them to functions that need to change them by reference indirectly through pointers to them.

For example

void get_q (int *a, int *b, char* q){
    if(strstr(q, "somestring1")!=NULL){
        *a=1;
        *b=0;
    //...

int main (int argc, char **argv){
    int a, b;

    get_q( &a, &b, argv[1]);
    //...

A:so you need to check that argv[1] is not a null pointer.

  • Related