Difference between static in C and static in C++?? - c++

What is the difference between the static keyword in C and C++?

The static keyword serves the same purposes in C and C++.
When used at file level (outside of a function), it sets the visibility of the item it's applied to. Static items are not visible outside of their compilation unit (e.g., to the linker). Their duration is the same as the duration of the program.
These file-level items (functions and data) should be static unless there's a specific need to access them from outside (and there's almost never a need to give direct access to data since that breaks the central tenet of encapsulation).
If (as your comment to the question indicates) this is the only use of static you're concerned with then, no, there is no difference between C and C++.
When used within a function, it sets the duration of the item. Again, the duration is the same as the program and the item continues to exist between invocations of that function.
It does not affect the visibility of that item since it's visible only within the function. An example is a random number generator that needs to keep its seed value between invocations but doesn't want that value visible to other functions.
C++ has one more use, static within a class. When used there, it becomes a single class variable that's common across all objects of that class. One classic example is to store the number of objects that have been instantiated for a given class.
As others have pointed out, the use of file-level static has been deprecated in favour of unnamed namespaces. However, I believe it'll be a cold day in a certain warm place before it's actually removed from the language - there's just too much code using it at the moment. And ISO C have only just gotten around to removing gets() despite the amount of time we've all known it was a dangerous function.
And even though it's deprecated, that doesn't change its semantics now.

The use of static at the file scope to restrict access to the current translation unit is deprecated in C++, but still acceptable in C.
Instead, use an unnamed namespace
namespace
{
int file_scope_x;
}
Variables declared this way are only available within the file, just as if they were declared static.
The main reason for the deprecation is to remove one of the several overloaded meanings of the static keyword.
Originally, it meant that the variable, such as in a function, would be given storage for the lifetime of the program in an area for such variables, and not stored on the stack as is usual for function local variables.
Then the keyword was overloaded to apply to file scope linkage. It's not desirable to make up new keywords as needed, because they might break existing code. So this one was used again with a different meaning without causing conflicts, because a variable declared as static can't be both inside a function and at the top level, and functions didn't have the modifier before. (The storage connotation is totally lost when referring to functions, as they are not stored anywhere.)
When classes came along in C++ (and in Java and C#) the keyword was used yet again, but the meaning is at least closer to the original intention. Variables declared this way are stored in a global area, as opposed to on the stack as for function variables, or on the heap as for object members. Because variables cannot be both at the top level and inside a class definition, extra meaning can be unambiguously attached to class variables. They can only be referenced via the class name or from within an object of that class.

It has the same meaning in both languages.
But C++ adds classes. In the context of a class (and thus a struct) it has the extra meaning of making the method/variable class members rather members of the object.
class Plop
{
static int x; // This is a member of the class not an instance.
public:
static int getX() // method is a member of the class.
{
return x;
}
};
int Plop::x = 5;

Note that the use of static to mean "file scope" (aka namespace scope) is only deoprecated by the C++ Standard for objects, not for functions. In other words,:
// foo.cpp
static int x = 0; // deprecated
static int f() { return 1; } // not deprecated
To quote Annex D of the Standard:
The use of the static keyword is
deprecated when declaring objects in
namespace scope.

You can not declare a static variable inside structure in C... But allowed in Cpp with the help of scope resolution operator.
Also in Cpp static function can access only static variables but in C static function can have static and non static variables...😊

Related

Why C++ static data members are needed to define but non-static data members do not?

I am trying to understand the difference between the declaration & definition of static and non-static data members. Apology, if I am fundamentally miss understood concepts. Your explanations are highly appreciated.
Code Trying to understand
class A
{
public:
int ns; // declare non-static data member.
static int s; // declare static data member.
void foo();
};
int A::s; // define non-static data member.
// int A::ns; //This gives an error if defined.
void A::foo()
{
ns = 10;
s = 5; // if s is not defined this gives an error 'undefined reference'
}
When you declare something, you're telling the compiler that the name being declared exists and what kind of name it is (type, variable, function, etc.) The definition could be with the declaration (as with your class A) or be elsewhere—the compiler and linker will have to connect the two later.
The key point of a variable or function definition is that it tells the compiler and linker where this variable/function will live. If you have a variable, there needs to be a place in memory for it. If you have a function, there needs to be a place in the binary containing the function's instructions.
For non-static data members, the declaration is also the definition. That is, you're giving them a place to live¹. This place is within each instance of the class. Every time you make a new A object, it comes with an ns as part of it.
Static data members, on the other hand, have no associated object. Without a definition, you've got a situation where you have N instances of A all sharing the same s, but nowhere to put s. Therefore, C++ makes you choose one translation unit for it via a definition, most often the source file that acommpanies that header.
You could argue that the compiler should just pick one instance for it, but this won't work for various reasons, one being that you can use static data members before ever creating an instance, after the last instance is gone, or without having instances at all.
Now you might wonder why the compiler and linker still can't just figure it out on their own, and... that's actually pretty much what happens if you slap an inline on the variable or function. You can end up with multiple definitions, but only one will be chosen.
1: Giving them a place to live is a little beside the point here. All the compiler needs to know when it creates an object of that class is how much space to give it and which parts of that space are which data members. You could think of it as the compiler doing the definition part for you since there's only one place that data member could possibly live.
static members are essentially global variables with a special name and access rules tied to the class. Hence, they inherit all the problems for usual global variables. Namely, in the whole C++ program (which is the union of all translation units aka .cpp files) there should be exactly one definition of each global variable, no more.
You can think of "variable definition" as "the place which will allocate memory for the variable".
However, classes are typically defined in a header file (.h/.hpp/etc) which is included in multiple translation units. So it's up to the programmer to specify which translation unit actually defines the variable. Note that since C++17 we have the inline keyword which places this burden on a compiler, look for "inline variables". The naming is weird for historical reasons.
However, non-static members do not really exist until you create an instance of the class, i.e. an object. And it's the object lifetime and storage duration which define how each individual member is created/stored/destroyed. So there is no need to actually define them anywhere outside of the class.
static variables belongs to the class definition. non-static variables belong to the instances created with the class definition.
int main()
{
A::s = 5; // this is ok
A a;
a.ns = 5 // this is also ok
}

CreateTimerQueueTimer termination on WM_CLOSE [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know the keyword in c has two usage:
modify variables
modify global variables
this usage limited the scope of global variable range from the point that defined to the end of the file.
modify local variables
this usage limited the scope of local variable in the function that defined, but also remained in the static area of memory
modify functions
this means can only invoke the function in the file it's defined.
and in c++, beside the usage in c, static also used to modify the data member and function member of class. This usage limited the member belong to the class instead of the objects of the class.
I want to know are there anything else usage of static in c/c++?
static is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
Within functions, static is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
says that the value of i will be preserved between calls to f(). Other storage classes are the default auto (but beware the change in meaning in C++11), extern, and register, plus thread_local in C11/C++11.
At file scope (or namespace scope in C++), static is a linkage specifier. Functions and variables marked static in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
can only be referenced by other functions inside the same .c file. This usage of static was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
One last one: in C99 (but not C++), static can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
this specifies that the parameter a must by an integer array of size at least 4.
I think that's all of them, but let me know in the comments if there are any I've forgotten!
Static In the C language family, a static variable is one that exists for the lifetime of a compilation
unit (a source file or module). A static variable can be declared module-wide, and thus be
accessed by all functions defined within the same source file. Such a static variable cannot
be directly accessed from other modules, but inner-module API can pass pointers to static variables and
modify those through pointers. A static variable can also be declared within a function body, where the
usual scope rules apply. A static variable declared within a function is only initialized when
the module is initialized (typically when the application loads), and preserves its values over multiple
invocations of the function that contains the definition.
In C++, a static variable can also be a member of a class definition. Access to a static member
variable is governed by the standard access modifiers (private, public, protected), but all instances of
this class share the same static variable, and share the same value. Modifying the value of this variable
affects all objects of the class. VolatileThe volatile keyword is something all together different, and not in any way
an opposite to static. A static variable may or may not be declared volatile, just as a global or local variable
can be. The volatile keyword is a hint informing the compiler that the variable's value
might change without the compiler's knowledge. Therefore, the compiler's code optimizer cannot make assumptions
about the variable's current value, and must always (re-) read the variable's content.
In reference to c++ -> The static keyword can be used to declare variables, functions, class data members and class functions.
Here are the common usages in different scenarios ( ref from MSDN )
When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.
When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const static can have an initializer.
When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.
check following also:
The static keyword and its various uses in C++
static keyword usage

is static const in C++ same as const in C? [duplicate]

This question already has answers here:
Static variables in C++
(3 answers)
Closed 8 years ago.
In C header file:
const int AvarInC = 1;
Now in C++ file:
class Cpp
{
public:
static const int PublicAvar = 1;
private:
static const int Avar = 1;
};
while i have:
const int AvarInC = 1; in my C headers
OR
static const int AvarInC = 1; in my C headers.
Will it be the same thing? Is the first one without keyword static, implicitly static?
It is similar. Of course, you can use the C way in C++ as well.
But the specific C++ way (a class member) also differs in visibility and scope. Only code that is part of class Cpp (or a friend) can access Avar. The PublicAvar is somewhere in between; anyone can access it, but they need to refer to it as Cpp.PublicAvar.
The keyword static has two distinct meanings in C++. Sometimes it means the storage class (as in your example) - that is, "this is not a per-instance member". In this respect, a variable which is not a member of a class at all is obviously static without having to declare that.
Other times, static may refer to link-time visibility. A static symbol is only valid inside its own compilation unit. That's the original C meaning. It does not come into your example especially because we are assuming that your code goes in a header file, and is therefore present in multiple compilation units. Marking a non-member variable as static would result in a number of copies of the variable in the program (one per compilation unit) which would not hurt for a const variable, but generally it could lead to very confusing program behavior.
If I understand you correctly, no they aren't quite the same. Since you are putting the C one in a header file, I'm assuming it will be a global constant, therefore there will really only be one copy of it anyways. It won't need to be recreated each time (since that what static will do.
However, the one in the C++ file is inside a class and static, so every time that class is instantiated into an object all instances will share the same copy of the PublicAvar variable and it won't get recreated with each object.
Though, I have a feeling you knew what static does. So technically no, they don't do the same thing and aren't the same thing...but they do act similarly.
I'm not an expert, so I could be wrong but I believe this is right. Hope it helps.
No, they are not same. They are both variables are initialized at compile time. But static variable can be accessed without creating any object of a class, but non static variable only exists within an object. i.e, the static variable takes common space in the memory for any number of objects created for it, but not in case of the other one.
"The same" is quite ambiguous. Both will be treated as compile-time constant. You can (should) not change them at runtime and the compiler can decide to use this information to optimize your code.

what's the difference meaning of the keyword static between c and c++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know the keyword in c has two usage:
modify variables
modify global variables
this usage limited the scope of global variable range from the point that defined to the end of the file.
modify local variables
this usage limited the scope of local variable in the function that defined, but also remained in the static area of memory
modify functions
this means can only invoke the function in the file it's defined.
and in c++, beside the usage in c, static also used to modify the data member and function member of class. This usage limited the member belong to the class instead of the objects of the class.
I want to know are there anything else usage of static in c/c++?
static is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
Within functions, static is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
says that the value of i will be preserved between calls to f(). Other storage classes are the default auto (but beware the change in meaning in C++11), extern, and register, plus thread_local in C11/C++11.
At file scope (or namespace scope in C++), static is a linkage specifier. Functions and variables marked static in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
can only be referenced by other functions inside the same .c file. This usage of static was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
One last one: in C99 (but not C++), static can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
this specifies that the parameter a must by an integer array of size at least 4.
I think that's all of them, but let me know in the comments if there are any I've forgotten!
Static In the C language family, a static variable is one that exists for the lifetime of a compilation
unit (a source file or module). A static variable can be declared module-wide, and thus be
accessed by all functions defined within the same source file. Such a static variable cannot
be directly accessed from other modules, but inner-module API can pass pointers to static variables and
modify those through pointers. A static variable can also be declared within a function body, where the
usual scope rules apply. A static variable declared within a function is only initialized when
the module is initialized (typically when the application loads), and preserves its values over multiple
invocations of the function that contains the definition.
In C++, a static variable can also be a member of a class definition. Access to a static member
variable is governed by the standard access modifiers (private, public, protected), but all instances of
this class share the same static variable, and share the same value. Modifying the value of this variable
affects all objects of the class. VolatileThe volatile keyword is something all together different, and not in any way
an opposite to static. A static variable may or may not be declared volatile, just as a global or local variable
can be. The volatile keyword is a hint informing the compiler that the variable's value
might change without the compiler's knowledge. Therefore, the compiler's code optimizer cannot make assumptions
about the variable's current value, and must always (re-) read the variable's content.
In reference to c++ -> The static keyword can be used to declare variables, functions, class data members and class functions.
Here are the common usages in different scenarios ( ref from MSDN )
When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.
When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const static can have an initializer.
When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.
check following also:
The static keyword and its various uses in C++
static keyword usage

when to declare an member of class

According to Bjarne Stroustrup:
if (and only if) you use an initialized member in away that requires it to be stored as an oject in memory ,the member must be(uniquely) defined somewhere. The initializer may not be repeated.
(The C++ Programming Language, 3rd Edition, Section 10.4.6.1)
He gives this example:
class curious{
public:
static const int c1=7;
//..
};
const int curious::c1; //necessary
Then why it is necessary to define a static member, because we may not be initializing it at all?
Also, const and reference members are not declared anywhere, even though it is necessary to initialize them (no default constructor).
If you don't use c1 in a way that requires it to be stored in memory (such as taking the address, etc) the compiler can replace all uses of c1 with the value 7. However, if you use it in such a way that it needs to be stored somewhere, then you have to provide a definition so that it exists in some compilation unit.
Member variables are not declared anywhere because they exist inside the object when it is created; each member variable lives inside the object that is created. static variables exist apart from any object instance (that is, the static variable exists regardless of whether the class is instantiated or not) so they need somewhere to live (sometimes) which is independent of a specific instance.