This question already has answers here:
Direct Initialization vs Copy Initialization for Primitives
(4 answers)
Closed 5 years ago.
Recently I saw a quite old code in C++, where int var(12) was used instead of int var=12. Why does it work? And should I avoid writing this style of declaration?
There are three ways of initializing variables are valid in C++.
type identifier = initial_value;
For example, to declare a variable of type int called x and initialize it to a value of zero from the same moment it is declared, we can write:
int a=5; // initial value: 5
type identifier (initial_value);
A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (()):
int b(3); // initial value: 3
type identifier {initial_value};
Finally, a third method, known as uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011):
int c{2}; // initial value: 2
You should check Documentation section Initialization of variables
This question already has answers here:
When should you use constexpr capability in C++11?
(15 answers)
Closed 6 years ago.
So I understand that the use of constexpr in C++ is for defined expressions that are be evaluated at compile time, and more obviously to declare a variable or function as a constant expression. My confusion comes from understanding any benefits of using it for simple functions that will not change.
Suppose you have a function to simply square a value...
int square(int x) {
return x * x;
}
Typically that will never change, or be overridden, however, I've seen people say that it would be better practice to instead define it as...
constexpr int square(int x) {
return x * x;
}
To me, this seems like such a trivial change. Can anyone enlighten me on serious advantages of declaring such simple expressions as constexpr?
The advantage of that change is that whenever x is known at compile time, result of square could be used to initialize constexpr variables or as a template argument.
This question already has answers here:
Is f(void) deprecated in modern C and C++? [duplicate]
(6 answers)
Closed 6 years ago.
I have seen in C++ program, during function declaration if there is no parameter for the function void is declared as parameter like this:
int F1(void)
How is it different than:
int F1()
There is no difference. Using void is just a more explicit way to declare the same thing. Personally, I never use that syntax and rarely see anyone else use it either.
It's the same thing in C++, and is a holdover from C.
Here's an excerpt from the C++ 2003 standard (C.1.6):
Change: In C++, a function declared with an empty parameter list takes no arguments.
In C, an empty parameter list means that the number and type of the function arguments are unknown"
Example:
int f(); // means int f(void) in C++
// intf(unknown) in C
Rationale: This is to avoid erroneous function calls (i.e. function calls with the wrong number or type of arguments).
Effect on original feature: Change to semantics of well-defined feature. This feature was marked as “obsolescent” in C.
Both of them are exactly the same, leaving the argument field empty as () is the one I prefer, some prefer writing (void) just so that someone editing the code may be ensured that no arguments are required. Makes no difference though, just a readability thing.
This question already has answers here:
What are the advantages of list initialization (using curly braces)?
(5 answers)
Closed 9 years ago.
I saw a initialization syntax which is new for me. I searched on google and here but I couldn't find something useful.
int a = 0;
int a = {0};
int a{0}; // <- this is new for me
Why do I need third style while others exist? What is the difference between each exactly?
Thanks.
You may be interested by C++11 initializer lists. They might not explain the third example, but they are useful, especially for real class objects.
Your code int a{0}; is called uniform initialization in C++11. See also most vexing parse wikipage (as commented by Joe Z).
Take time to at least read the C++11 wikipage. The new features of C++11 makes it almost a different language than C++03.
This form of initialization is referred to as list initialization in C++11.
When used with variables of built-in type, list initialization is different in one way: you can't list initialize variables of built-in type if the initializer might lead to the loss of information.
double pi = 3.1415926;
int a(pi); //fine
int a{pi}; //compile error
Note this question was originally posted in 2009, before C++11 was ratified and before the meaning of the auto keyword was drastically changed. The answers provided pertain only to the C++03 meaning of auto -- that being a storage class specified -- and not the C++11 meaning of auto -- that being automatic type deduction. If you are looking for advice about when to use the C++11 auto, this question is not relevant to that question.
For the longest time I thought there was no reason to use the static keyword in C, because variables declared outside of block-scope were implicitly global. Then I discovered that declaring a variable as static within block-scope would give it permanent duration, and declaring it outside of block-scope (in program-scope) would give it file-scope (can only be accessed in that compilation unit).
So this leaves me with only one keyword that I (maybe) don't yet fully understand: The auto keyword. Is there some other meaning to it other than 'local variable?' Anything it does that isn't implicitly done for you wherever you may want to use it? How does an auto variable behave in program scope? What of a static auto variable in file-scope? Does this keyword have any purpose other than just existing for completeness?
In C++11, auto has new meaning: it allows you to automatically deduce the type of a variable.
Why is that ever useful? Let's consider a basic example:
std::list<int> a;
// fill in a
for (auto it = a.begin(); it != a.end(); ++it) {
// Do stuff here
}
The auto there creates an iterator of type std::list<int>::iterator.
This can make some seriously complex code much easier to read.
Another example:
int x, y;
auto f = [&]{ x += y; };
f();
f();
There, the auto deduced the type required to store a lambda expression in a variable.
Wikipedia has good coverage on the subject.
auto is a storage class specifier, static, register and extern too. You can only use one of these four in a declaration.
Local variables (without static) have automatic storage duration, which means they live from the start of their definition until the end of their block. Putting auto in front of them is redundant since that is the default anyway.
I don't know of any reason to use it in C++. In old C versions that have the implicit int rule, you could use it to declare a variable, like in:
int main(void) { auto i = 1; }
To make it valid syntax or disambiguate from an assignment expression in case i is in scope. But this doesn't work in C++ anyway (you have to specify a type). Funny enough, the C++ Standard writes:
An object declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default. [Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (6.8) explicitly. — end note]
which refers to the following scenario, which could be either a cast of a to int or the declaration of a variable a of type int having redundant parentheses around a. It is always taken to be a declaration, so auto wouldn't add anything useful here, but would for the human, instead. But then again, the human would be better off removing the redundant parentheses around a, I would say:
int(a);
With the new meaning of auto arriving with C++0x, I would discourage using it with C++03's meaning in code.
The auto keyword has no purpose at the moment. You're exactly right that it just restates the default storage class of a local variable, the really useful alternative being static.
It has a brand new meaning in C++0x. That gives you some idea of just how useless it was!
GCC has a special use of auto for nested functions - see here.
If you have nested function that you want to call before its definition, you need to declare it with auto.
"auto" supposedly tells the compiler to decide for itself where to put the variable (memory or register). Its analog is "register", which supposedly tells the compiler to try to keep it in a register. Modern compilers ignore both, so you should too.
I use this keyword to explicitly document when it is critical for function, that the variable be placed on the stack, for stack-based processors. This function can be required when modifying the stack prior to returning from a function (or interrupt service routine).
In this case I declare:
auto unsigned int auiStack[1]; //variable must be on stack
And then I access outside the variable:
#define OFFSET_TO_RETURN_ADDRESS 8 //depends on compiler operation and current automatics
auiStack[OFFSET_TO_RETURN_ADDRESS] = alternate_return_address;
So the auto keyword helps document the intent.
According to Stroustrup, in "The C Programming Language" (4th Edition, covering C 11), the use of 'auto' has the following major reasons (section 2.2.2) (Stroustrup words are quoted):
1)
The definition is in a large scope where we want to make the type
clearly visible to readers of our code.
With 'auto' and its necessary initializer we can know the variable's type in a glance!
2)
We want to be explicit about variable's range or precision (e.g., double rather than float)
In my opinion a case that fits here, is something like this:
double square(double d)
{
return d*d;
}
int square(int d)
{
return d*d;
}
auto a1 = square(3);
cout << a1 << endl;
a1 = square(3.3);
cout << a1 << endl;
3)
Using 'auto' we avoid redundancy and writing long type names.
Imagine some long type name from a templatized iterator:
(code from section 6.3.6.1)
template<class T> void f1(vector<T>& arg) {
for (typename vector<T>::iterator p = arg.begin(); p != arg.end(); p)
*p = 7;
for (auto p = arg.begin(); p != arg.end(); p)
*p = 7;
}
In old compiler, auto was one way to declare a local variable at all. You can't declare local variables in old compilers like Turbo C without the auto keyword or some such.
The new meaning of the auto keyword in C++0x is described very nicely by Microsoft's Stephan T. Lavavej in a freely viewable/downloadable video lecture on STL found at MSDN's Channel 9 site here.
The lecture is worth viewing in its entirety, but the part about the auto keyword is at about the 29th minute mark (approximately).
Is there some other meaning to 'auto' other than 'local variable?'
Not in C++03.
Anything it does that isn't implicitly done for you wherever you may want to use it?
Nothing whatsoever, in C++03.
How does an auto variable behave in program scope? What of a static auto variable in file-scope?
Keyword not allowed outside of a function/method body.
Does this keyword have any purpose [in C++03] other than just existing for completeness?
Surprisingly, yes. C++ design criteria included a high degree of backward compatibility with C. C had this keyword and there was no real reason to ban it or redefine its meaning in C++. So, the purpose was one less incompatibility with C.
Does this keyword have any purpose in C other than just existing for completeness?
I learned one only recently: ease of porting of ancient programs from B. C evolved from a language called B whose syntax was quite similar to that of C. However, B had no types whatsoever. The only way to declare a variable in B was to specify its storage type (auto or extern). Like this:
auto i;
This syntax still works in C and is equivalent to
int i;
because in C, the storage class defaults to auto, and the type defaults to int. I guess that every single program that originated in B and was ported to C was literally full of auto variables at that time.
C++03 no longer allows the C style implicit int, but it preserved the no-longer-exactly-useful auto keyword because unlike the implicit int, it wasn't known to cause any trouble in the syntax of C.