Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Private Variables Get and Set methods

I am working in C, and have some variables that I don't want to be global, but I do want to have get and set methods for them that can be accessed "Globaly" outside of the file. I am used to doing this in Java, but C is very different in this manner. Basically I am looking for something that follows this pseudo Code, but I have not been able to find anywhere with examples that I might look at.

main.c
#include data.h
set(b);

datalog.c
#include data.h
get(b);

data.c
private int c;
set(b){
    c = b;
}
get(c){
    return c;
}
like image 848
Reid Avatar asked Apr 25 '12 16:04

Reid


People also ask

Can private variables be accessed by methods?

They are private in that they can only be accessed by that class. This means they are accessible from static methods of that class (such as main ) and also from instance methods (such as showData ). One instance of the class can also access private members of another instance of the class.

What is the use of private variables even though they are accessible via getters and setters from some other class?

In classes, variables are often made private for encapsulation, and to limit the variables to a certain scope allow better error control and fewer bugs. This makes sense, as the fewer places a variable can be accessed the fewer places a bug can occur with that variable.

How do you access private class variables?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class. Example: using System; using System.

Does C have private variables?

If you want private variables in c, there are a number of techniques that can approximate a private variable, but the C language actually doesn't have a "protection" concept that extends to private, public, protected (as C++ does).


1 Answers

You make the variable static. When a global variable is made static, its scope is restricted to the current file.

An example is as follows:

Filename: main.c

#include <stdio.h>

#include "header.h"

extern int get();
extern void set(int);

int main()
{
    set(10);
    printf("value = %d \n", get());   
    set(20);
    printf("value = %d \n", get());   
    set(30);
    printf("value = %d \n", get());   
    set(40);
    printf("value = %d \n", get());   
    return 0;
}

Filename: header.h

#include <stdio.h>

int get(void);
void set(int);

Filename: header.c

#include "header.h"

static int value = 0;

int get(void)
{
    return value;
}

void set(int new_value)
{
    value = new_value;
}

Output:

$ gcc -Wall -o main main.c header.h header.c 
$ ./main 
value = 10 
value = 20 
value = 30 
value = 40 
$ 
like image 160
Sangeeth Saravanaraj Avatar answered Sep 23 '22 01:09

Sangeeth Saravanaraj