const integer simple [closed] - c++

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.

Related

Should I use the 'const' keyword 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 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.

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.

Behavior when trying to change values of global and local const in C++ [duplicate]

This question already has answers here:
Can we change the value of an object defined with const through pointers?
(11 answers)
Closed 5 years ago.
I'm learning C++ from past few days and when learning about the const qualifier tried the below:
const int m = 10;
int main()
{
int* lptr;
int* gptr;
const int i = 20;
lptr = (int *)&i;
*lptr = 40; //line 1
cout<<i<<endl;
cout<<*lptr<<endl;
*gptr = (int*)&m;
*gptr = 50; //line 2
cout<<m<<endl;
cout<<*gptr<<endl;
}
Here, since I'm casting the const int* to int* explicitly, the code compilation is perfectly alright. In line 1, I'm surprised to see that there is no run time error(access violation). But in line 2 there is a run time error saying write access violation (which is expected as const variables are placed in ro memory). But here why the local const variable is allowed to be modified through lptr. Is there nothing like a read only memory on the stack also? (and if it doesn't then how safe is using const local variables as it can be modified with a pointer)
*I'm using MSVC++ 14.0 *
I know that const variables are not meant to be modified, but since I'm leaning from basics I'm exploring the different ways
Just because you can cast away const and then write to a const variable through a pointer to non-const does not make it legal. In fact it is undefined behaviour and your program is ill formed and has no meaning. The compiler is free to generate whatever code it feels like in that case.

Setting two variables *always* equal? [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 5 years ago.
Improve this question
After doing:
int a = 2;
int b = a;
a = 4;
b remains 2, which is very logical and in most of the cases very useful.
Is there any way for a and b to have always the same value, meaning that when one of them changes, the other also gets the same value?
For example:
//magic I am looking for
a = 2;
// now also b is equal to 2
b = 3;
// now also a is equal to 3
closest I could get (you can ignore this, it may not be leading anywhere):
int a =2;
int *ptr = &a;
int *b = ptr;
a = 9;
cout << *b;
and *b is 9, changing *b into 9 makes also a == 9.
but a and *b are not the same data type (int and pointer int), and I can't seem to get it to work within a list.
Edit: I didn't specify the language cause I wasn't sure in which one this could exist. It looks like C++ has some similar features (references) like the one I am looking for.
My only concern is that also references aren't working within an array, like my above solution.
If you are asking about C++, you can use references
int a = 2;
int& b = a;
a = 4; // now b also == 4
Otherwise if both are of type int, each variable contains its own value at its own memory location, and does not "know" about the other, nor will updating one modify the other.
If you are asking about C, you can't link two variables together that way.
You can however create multiple pointers to that variable. Then when you dereference any of those pointers you see the results reflected.
int a = 1;
int *b = &a;
int *c = &a;
int a = 2;
printf("*b=%d, *c=%d\n", *b, *c);
Output:
*b=2, *c=2

Can i somehow access a value if i know its address? [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
say we have a variable
int var = 3000;
int *pt;
pt=2293572; //where &var=2293572
Question is basically indirectly accessing values stored at memory locations, by just knowing the memory address?
If not in c,cpp can we use some other language for it?
It sounds like you are asking how to cast an integer to a pointer and assign a value to a memory location using it.
int var = 3000;
int *pt;
pt= (int*) 2293572;
// Assignment
*pt = 2; // now var = 2
Note that when you do this, you should observe the usual caveats, as Matt McNabb mentioned below.
whether the cast works is implementation-defined
the address might not be correctly aligned for int
you'd better make sure you have the right address
While running this program you might have got the address 2293572 for "var", but its not necessary that you will get the same address every time you run your program.
Therefore its not a good practice to, explicitly assign an address to a variable and then try to access the value at that address.
You need to use pointers if you want to play around with addresses in c
Try this :
#include<stdio.h>
int main()
{
int var = 100; // initialise a variable
int *ptr; // declare a pointer variable; a pointer is used to store the address
// (logical address, to be specific ) of a variable.
ptr = &var; // assign the address of the variable to the pointer
printf("\nvar = %d", *ptr); // access the value stored at that address. This is also
// dereferencing.
}
The correct way for the example given in your question:
int var = 3000;
int *pt = &var;
int x = *pt; // read-access (same as 'int x = var')
*pt = 12345; // write-access (same as 'var = 12345')
If you have a "pure" address (without the name of the variable allocated at that address):
int *pt = (int*)2293572;
int x = *pt; // read-access
*pt = 12345; // write-access
If the underlying HW architecture or the designated compiler at hand do not support unaligned load/store operations, then you have to ensure that the address is divisible by the size of the data-type.
For example, in the above code you would have to assert that 2293572 % sizeof(int) == 0.
Int car = 3000; //variable car
Int final;
Int* ptr; // unassigned pointer
Ptr= &car; // variable ptr holds memory location of car.
final = *ptr // this is the dereference
Final will return the integer value 3000.
To be quick and simple, pointers point to memory locations. When you "dereference" you say..."Hey I don't want to know where the number is, I want to know what value is stored there.
The tricky part of c is that it uses dynamic memory allocation, so it will not maintain the same location every time.