not able to understand the working of static concept here in

In Java, a static method is associated with the class and may be called without an instance. And therefore cannot access instance variables either.

In c++, static keyword has several meanings depending on context. A static member function (which is what class methods are typically called in c++) is quite similar to static methods in Java in respect of the above description.

However, neither int main() nor int static t() is a member function at all. They’re free functions, not associated with any class. Declaring a free function static gives it internal linkage. Which means that it will not be visible to functions in other compilation units (.cpp files).

The functions being static or non-static affects in no way how t() works in either version of your code. You always print a local variable and increment it. Since the variable does not have static storage duration (another use for the keyword static) nor is it a member of an object instance, but an automatic local variable, it is destroyed as soon as the function call ends and therefore the incremented value is never used for anything. On the other hand, if the variable was declared static, then you’d get output “1 2 3”.

In Java, there is no free functions nor local variables with static storage duration.

Leave a Comment