473,785 Members | 2,476 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question on const

Hello,

Here is the program

#include stdio

int main(void)
{
const int num = 100;
int *ip;

ip = (int *)#
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
}
Output:
value of num is 100(200)

The output says that *ip is changed and 'num' is unchanged. How is this
possible when both of them point to the same memory location? My wild guess
says that this trick is handled at the compiler level. Am I correct?

Even when the memory location is accessable and the contents changed the
'const integer' is unaffected.

Thanks
Nov 14 '05 #1
83 3067

"user" <no**@none.co m> wrote in message news:3f******@u senet01.boi.hp. com...
Hello,

Here is the program

#include stdio

#include <stdio.h>
int main(void)
{
const int num = 100;
int *ip;

ip = (int *)&num;
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
return 0;
}
Output:
value of num is 100(200)


On my system the output is

value of num is 200(200)

[..]
Nov 14 '05 #2
Hello,

I am sorry. After reading the post myself, I felt that the post is
incomplete in itself.

Well when I tried this exercise I expected the code to fail in the
compilation phase with an error ( not a warning). It did not, and the output
made me think how is this possible to have 2 different value when I am
pointing to the same memory location? I exptected the output to 2 100s or 2
200s. Is 'num' variable pointing some where ????

My question is how is the output different? Is the program performing an
undefined behavior?

Thanks

"user" <no**@none.co m> wrote in message news:3f******@u senet01.boi.hp. com...
Hello,

Here is the program

#include stdio

int main(void)
{
const int num = 100;
int *ip;

ip = (int *)&num;
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
}
Output:
value of num is 100(200)

The output says that *ip is changed and 'num' is unchanged. How is this
possible when both of them point to the same memory location? My wild guess says that this trick is handled at the compiler level. Am I correct?

Even when the memory location is accessable and the contents changed the
'const integer' is unaffected.

Thanks

Nov 14 '05 #3
I think the int* p find a new adress in order to write something to that
adress.
If you write const int* ip in that case the adress of ip can't change.
If you assign anything to int *ip it will be assigned to an adress which the
computer will find in order to store it there.

--

---------------------------
Time to get it done!

Remove (d*elete*) to reply

"user" <no**@none.co m> wrote in message news:3f******@u senet01.boi.hp. com...
Hello,

Here is the program

#include stdio

int main(void)
{
const int num = 100;
int *ip;

ip = (int *)&num;
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
}
Output:
value of num is 100(200)

The output says that *ip is changed and 'num' is unchanged. How is this
possible when both of them point to the same memory location? My wild guess says that this trick is handled at the compiler level. Am I correct?

Even when the memory location is accessable and the contents changed the
'const integer' is unaffected.

Thanks

Nov 14 '05 #4
"user" <no**@none.co m> writes:
#include stdio
Do you mean

#include <stdio.h>

?
int main(void)
{
const int num = 100;
int *ip;

ip = (int *)&num;
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
You forgot to return something from the `main' function. Insert

return 0;
}
The behavior of this program is undefined according to section 6.7.3#5 of
the standard: "If an attempt is made to modify an object defined with a
const-qualified type through use of an lvalue with non-const-qualified
type, the behavior is undefined. [...]"
Output:
value of num is 100(200)

The output says that *ip is changed and 'num' is unchanged. How is this
possible when both of them point to the same memory location?
Since the behavior is undefined, virtually anything can happen.
My wild guess says that this trick is handled at the compiler level. Am
I correct?


I don't know what you mean by "this trick".

Martin
Nov 14 '05 #5

"user" <no**@none.co m> wrote in message news:3f******@u senet01.boi.hp. com...
Hello,

I am sorry. After reading the post myself, I felt that the post is
incomplete in itself.

Well when I tried this exercise I expected the code to fail in the
compilation phase with an error ( not a warning). It did not, and the output made me think how is this possible to have 2 different value when I am
pointing to the same memory location? I exptected the output to 2 100s or 2 200s. Is 'num' variable pointing some where ????

My question is how is the output different? Is the program performing an
undefined behavior?

Thanks

"user" <no**@none.co m> wrote in message

news:3f******@u senet01.boi.hp. com...
Hello,

Here is the program

#include stdio

int main(void)
{
const int num = 100;
int *ip;

ip = (int *)&num;
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
}
Output:
value of num is 100(200)

The output says that *ip is changed and 'num' is unchanged. How is this
possible when both of them point to the same memory location? My wild

guess
says that this trick is handled at the compiler level. Am I correct?

Even when the memory location is accessable and the contents changed the
'const integer' is unaffected.

Thanks


Hello,

Sorry for top posting (in my earlier post). I am trying this on a OpenVMS
Alpha system.

Thanks
Nov 14 '05 #6
Please don't top-post. Please don't put a lot of quoted material in your
signature. Your signature is 36 lines long, which is 32 lines more than
the allowed four lines.

"Frane Roje" <frane.roje(d*e lete*)@st.hinet .hr> writes:
I think the int* p find a new adress in order to write something to that
adress.
I'm not sure if I understand you correctly, but you seem to believe that
the definition of a pointer automatically allocates memory. That is not the
case.
If you write const int* ip in that case the adress of ip can't change.


Once you have defined a variable, pointer or other type, const-qualified
or not, its /address/ cannot change throughout its lifetime.

The /value/ of `ip' can certainly be changed. The object pointed to by
`ip' cannot (unless another access path to the same object exists).

Martin
Nov 14 '05 #7
On Thu, 08 Jan 2004 15:02:12 +0530, user wrote:
Well when I tried this exercise I expected the code to fail in the
compilation phase with an error ( not a warning). It did not, and the output
made me think how is this possible to have 2 different value when I am
pointing to the same memory location? I exptected the output to 2 100s or 2
200s. Is 'num' variable pointing some where ????


I'll try to explain this way:

#include <stdio.h>

int
main (void)
{
const int num = 100;
int *ip;

ip = (int *) &num;
*ip = 200;
printf ("value of num is %d(%d) \n", num, *ip);
printf ("address of ip is 0x%p\n", ip);
printf ("address of num is 0x%p\n", &num);
}

this will print out the addresses the pointers are pointing to.
The output is as expected: the address is the same.

Now, I'm not sure of what i'm about to say, but well, correct me if
I am wrong :)

I *think* that the problem is in what we had declared constant, or, better,
in what the compiler sees as a constant.

const int num = 100, we have declared the variable num, it's *name*,
to be constant. We cannot change the value *through that symbol*,
but nothing prevents us by changing it by other means.
Let's assume this declaration is the same as

int *const num = 100;

This is a constant pointer.
You cannot change it's address, but you can change the data.
The other way is

const int *num = 100;

Here the data is constant, we cannot change the data but we can change the
address the variable points to.
So, AFAIK, it may be correct to make the assumption that when we declare
a

const int num

we are actually declaring (or the compiler is actually going to change it
to) the former:

int *const num

that is a constant pointer. But sintactically we handle it as a normal
variable, with the constraint that we cannot change it's value
*through the symbol itself*, and being it a normal variable, and not a
pointer, we cannot either directly change it's address. But indirectly
we can.

So accessing it by

num = 100;

is only a sintactical error, because the compiler knows that that
*variable name* is constant.

I mean, I *think* that the compiler doesn't make assumptions on the data
pointed by that name, but only on the name itself.

Bye
Daniele "tinybyte" Milan

Nov 14 '05 #8
Martin Dickopp <ex************ ****@zero-based.org> writes:
I'm not sure if I understand you correctly, but you seem to believe that
the definition of a pointer automatically allocates memory. That is not the
case.


I noticed that my statement is ambiguous. To clarify, the definition of
a pointer automatically allocates memory for the pointer itself, but it
doesn't allocate any memory at the location the pointer points to.

Martin
Nov 14 '05 #9
[You have top-posted yet again. Please stop.]

Frane Roje wrote:
I think the int* p find a new adress in order to write something to that
adress.
I can't make sense of that at all.
If you write const int* ip in that case the adress of ip can't change.
When /can/ the address of a named object change?
If you assign anything to int *ip it will be assigned to an adress which the
computer will find in order to store it there.


I can't make sense of that either.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3694
by: Jessica | last post by:
Hi, I have a design question. I am making a time series analysis tool. Since I already use STL vector to represent time series, is there a need to implement a class for the time series object? Right now I just use typedef vector<double>TS; Is that enough? I feel that I am not taking advantage of the C++
7
5076
by: CoolPint | last post by:
While I was testing my understanding of Functioin Template features by playing with simple function templates, I got into a problem which I cannot understand. I would be very grateful if someone offered me a kind explanation. TIA Function template and specialization below works fine: template <typename T> T maximum (T a, T b) {
2
6381
by: fb | last post by:
Hi everyone. I have the following code. It was a question out of C++ how to program. I get a warning about "possible unreachable code" in the RunCode() function, but I don't see any problem with it... I was hoping for a better way of exiting the case statements below. I used exit() for "divide by zero" and "invalid instruction". I can't get a try/catch to work. Probably from a lack of experience. I have a fairly strong C...
2
2181
by: Harry | last post by:
Hi all, I am writing a logger program which can take any datatype. namespace recordLog { enum Debug_Level {low, midium, high}; class L { std::ofstream os; Debug_Level cdl; const Debug_Level ddl;
2
1936
by: Rouben Rostamian | last post by:
The main() function in the following code defines an m by n matrix, assigns value(s) to its elements, then passes the matrix to function foo(). For whatever it's worth, I have declared foo() so as to make it treat its first argument as a "read-only" object, that is, foo() can read but not alter the matrix. I have a problem, however, with /calling/ foo. If I call foo as foo(a,m,n), my compiler (gcc) complains about:
4
1746
by: JoeC | last post by:
I am trying to design some complex objects that have quite a bit of data. I understand most syntax but I am trying to learn how to make better design choices. The first question is to OK or good design to have large objects with several has-a relationship with other objects. Second, I want my unit to have a coord struct. struct coord{ int x;
14
1347
by: streamkid | last post by:
i'm a learning newbie at c++... and i have the following question... reading some source code, i saw this: int function(const void * one, const void * two) { int var1, var2; var1 = *((int*)one); var2 = *((int*)two); /* sm other code here*/ }
8
2237
by: indrawati.yahya | last post by:
In a recent job interview, the interviewer asked me how I'd design classes for the following problem: let's consider a hypothetical firewall, which filters network packets by either IP address, port number, or both. How should we design the classes to represent these filters? My answer was: class FilterRule {
14
2123
by: Alexander Dong Back Kim | last post by:
Dear all, I used to use C++ programming language at all time but moved to C# and Java. Few days ago, I restarted studying about C++ with a very beginner's mind. I wrote a simple class and gcc couldn't compile the class. Any hints that I'm missing? Header File: #ifndef __Calc_h__
8
1669
by: fabian.lim | last post by:
Hi, I have a question on constant variables. In the following code snippet, I have a function assign() that takes in an iterator to the private variable v, the number of stuff to assign (int n), and the information to assign (a const pointer to a class object Vector<TYPE>. According to the arrow below, I put a const keyword in the function. To my knowledge, this means that all private variables in this object
0
9489
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10357
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5396
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4063
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2893
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.