Should I use the 'const' keyword in c++ [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am new to C++ and have come across the const keyword. I looked it up online and read that The main use is to prevent the changing the value throughout the program. I have these two snippets below
const int size = 56;
Compared to using
int size = 56;
Why should I use one over the other? What is the idea behind using it.

Yes, you should make all variables const if you are never going to change its value after initialization. This prevents bugs where you accidentally change a value you're not supposed to. You seem to be aware of this already.
In addition, there is something that you might not be aware of, which is that making an int variable const also makes it a constant-expression, so long as the initializer itself is also a constant-expression, e.g. the int literal 56. This allows you to use it in contexts where you need a constant-expression, e.g. as the dimension of a static array:
const int size = 56;
int a[size]; // ok
int size = 56;
int a[size]; // error

In c++ CONST is used when you want to declare something which will not change its value throughout the program. But if you accidentally try to rewrite its value, the compiler will through an error. Most of the time it is recommended to declare a variable of int type so you can redefine its value when it's required. CONST is used when you want to declare a static array i.e.
const int a = 100;
int sampleAray[a];
And int is used when you, the value of the variable will be modified at some point i.e.
int a = 12;
int arr[4] = {11,22,33,554};
for (int i=0; i<4; i++){
if(arr[i]%2 == 0){
a+=arr[i];
}
}

When you have a const variable holding something that should not change and accidentally write code that modifies the variable anyway, you get a nice compiler error and can correct your mistake easily. If the variable is non-const, the compiler cannot help you and you now have a bug that may be hard to find.

Related

What am I missing in defining an array? [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 last year.
Improve this question
I have been trying to learn arrays and I can't seem to define an array.
const int size = 10;
??[size];
Can anybody spot my mistakes? Thank You.
To declare an array using a constant, you should use this syntax:
// constexpr is explicitly compile time constant
constexpr int size = 10;
int my_array[size]; // int array, can be changed to float
For dynamic array, use vector:
int size = ...;
std::vector<int> my_array;
array.resize(size);
You can also use modern statically sized array:
constexpr int size = 10;
std::array<int, size> my_array;
const int size = 10;
type array[size];
Is what you want. Substitute type for any type (i.e. int, float, bool etc.).
In this case, specifying array size using a const variable is valid, but there are many cases where it isn't. You'd probably want to learn the difference between const and constexpr.
Also, instead of learning by asking questions here, try finding a good c++ source: a book, online article series or a video tutorial. It'll definitely accelerate your education.

Variable declare & Assign value in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Is it possible to declare a variable without assigning value in C++?
int a; int a=15; Which one will be Correct?
If i assign value to a variable 3 times or more which one will count at the end in C++??
int a=15;
int a=10;
int a=5;
Which value will be execute for a at the end?
int a; // declared but not assigned
a = 1; // assigning a value
a = 2; // assigning a different value
a = 3; // assigning another value
std::cout << a << "\n"; // will print 3 since only the last assignment matters
int x; declares a variable x without assigning a value.
If you assign to a variable three times then which ever assignment executed last will be the variables final value. Very important idea, C++ statements execute in a specific order, and which order they execute in is essential to understanding what a program does.

Naming constants in C++ [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am replacing my #defines, for instance #define NUM_SLIDER_POSITIONS 5 for constant variables. Should I keep the old naming like:
const unsigned int NUM_SLIDER_POSITIONS = 5;
Or should I use something more like:
const unsigned int kNumSliderPositions = 5;
.
EDIT: The post has been put on hold, but anyway I'd like to sum up your answers:
Other option would be using underscores as a separators using lower case letters:
const unsigned int num_slider_positions = 5;
Constant identifier.
Regarding the use of a prefix as a way of identifying constants , the most common options are not using it, as it may not add relevant information:
const unsigned int num_slider_positions = 5;
Use a "k" before the name:
const unsigned int k_num_slider_positions = 5;
Or declaring the variable inside a class or namespace, in order to avoid polluting the global scope and providing a more self-explanatory name:
namespace defaults // or "config", or "settings" or something like that
{
const unsigned int num_slider_positions = 5;
}
Client code:
int slider_positions = defaults::num_slider_positions;
I am replacing my #defines for constant variables.
Kudos! :)
Should I keep the old naming like: [all-caps]
If the coding conventions of your project designate constants to be in all-caps, you should (as it spares you an effort). Otherwise, you should not (because it will be confusing later, for maintenance).
Or should I use something more like: [bastardized hungarian convention]
This is up to you. Personally I do not like to add weird letters for my constants, because when reading the code - or writing it - I do not care much that they are constant (and if I try to write into them, the compiler will let me know).
My (personal) choice would be to use a namespace for providing context (instead of a prefix), along these lines:
namespace defaults // or "config", or "settings" or something like that
{
const unsigned int num_slider_positions = 5;
}
Client code:
int slider_positions = defaults::num_slider_positions;
I find this to be a superior alternative, because the context is more self-explanatory (than a "k" in front of it, or a "g" or a whatever else).
It's up to you for any name convention. But for C++ code you may also consider putting constants inside a class that use it, instead of pollute the global scope.
the naming convention of constant name with C++ is use a k followed by mixed case,
for constants defined globally or within a class, As a convenience to the reader, compile-time constants of global or class scope follow a different naming convention from other variables. Use a k followed by words with uppercase first letters
const unsigned int kNumSliderPositions = 5;
see more

Pointer vs Return [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
Which is faster when assigning a variable via a method, to return a variable, or to point to a variable?
Case 1:
Function Declaration
void foo(int* number)
{
*number = 5;
}
Usage
int main()
{
int number;
function(&number);
cout << "Number: " << number;
}
Case 2:
Function Declaration
int foo()
{
int number = 5;
return number;
}
Usage
int main()
{
int number;
number = function();
cout << "Number: " << number;
}
PS: In case 2, I created a variable and returned it instantly. I know this doesn't make sense, but this is the closest example I can find for the situation I'm dealing with, since I'm initializing an actual object, which requires creating the object first, editing it, then returning it
It depends on the cost of copying the variable. For primitive types, return a value.
For more complex types consider passing in a reference, or take a look at the C++11 move semantics.
One benefit of using output parameters (Case 1) is it gives you the ability to have a function 'return' multiple values:
void foo (int* x, int* y)
{
*x = 5;
*y = 4;
}
But like everyone said in the comments, this doesn't matter in C++ as much as C.
Generally returns are far more readable and make your program's logic well defined and
easy to follow. In C++, stick to returns or references.
Typically, you should choose which to use on your needs rather than on performance.
Do you have multiple outputs? -> Use pointers
Is an input going to be an output -> Might as well use pointers
It's more difficult with these two scenarios to return a variable.
Other than that, performance-wise, it's only nice to use a variable when the variable is super complex, that way, you're only passing in a pointer instead of that super complex object. But any performance gain is negligible other than that.

const integer simple [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to go through C++ Intro
It's written there "• const int i = 3 // can’t change the value of const variable"
but my code
#include<iostream>
using namespace std;
int main()
{
const int i = 44;//trying
cout<<i;
return 0;
}
Works
Why ?
Also I use codeblocks In Windows 7
You never change the value of i, right?
const int i = 44; // initialization - OK
i = 44; // assignment - not OK
statement const int i = 3 tells the c++ compiler that i is a variable of type int which is a constant and has the value 3.
This means any further attempt to change the value of i will lead to compilation errors. in your sample code you cant change the value of i after the first initialization.
const means once set, you cannot change the value of that variable during the execution. But, the value can be set to anything the first time.
Your variable i is declared as const, which means that it can only be initialized, but cannot be changed later in code. It would, however, not make sense if all constants would have to have the value 3, don't you agree? So when initializing, you can set it to any integer value you like; but the compiler won't allow you to change it later in your code; try this, it will give you a compiler error:
const int i = 3;
// ...
i = 44; // <- here the compiler will complain, saying that i was declared const
It works because you have not changed the value of "i" in your code
const int i = 44; // Initialization of a const value, OK.
cout << i; // Just reading the value, this is OK
i = 44; // This will not work because you can't change the value of a const type.
It works because there's a difference in C++ between initialization and assignment.
When you declare a variable, you can choose to initialize it:
int i; // i is uninitialized
int j = 42; // j is initialized
after this point, once the variable exists, you can no longer initialize it. It has whatever value it has now (i has some random garbage value, and j has the value 42). All you can do instead is assign a new value to it:
i = 43;
j = 44;
When a variable is const, you can't assign a new value to it. You can still initialize it, but once it has been initialized, it can never change.
So const int i = 44 is perfectly valid, because you are initializing a new variable, rather than assigning a new value to an existing variable.