Home > Mobile >  Can a variable and a method have the same name in C ?
Can a variable and a method have the same name in C ?

Time:01-19

class Controller {

 bool isBackendActive();
 void anotherMethodDoingSomething();

}

Can I declare a boolean variable with the same name as a method so that I can use it like this:

void Controller::anotherMethodDoingSomething() {
    bool isBackendActive = isBackendActive();
    if (aBoolean && isBackendActive) {
     ...
     LOG("bla"   isBackendActive)
    }
    else if (!isBackendActive) {
     ...
    }
    else 
     ...
    }
    

Thank you a lot for your input in advance.

CodePudding user response:

Without discussing merits (or lack thereof), yes, you can disambiguate a member from a local variable rather easily.

bool const isBackendActive = this->isBackendActive();

or

bool const isBackendActive = Controller::isBackendActive();

Will work (and might as well be const correct).

CodePudding user response:

You can see the compiler error messages:

 error: 'isBackendActive' cannot be used as a function
   43 |         bool isBackendActive = isBackendActive( );
      |                                ~~~~~~~~~~~~~~~^~~

It's not possible.

You can rename your function using snake_case to make them different:

bool is_backend_active( );

If you don't want to do that then:

bool isBackendActive = this->isBackendActive( );

Use of this will give the compiler enough info about what you want. It tells the compiler that you want to have access to a member (a variable or a function) of the class Controller and not a local variable like bool isBackendActive;

  •  Tags:  
  • Related