473,797 Members | 3,096 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
83 3070
On Thu, 08 Jan 2004 14:57:21 +0530, Vijay Kumar R Zanvar wrote:
On my system the output is

value of num is 200(200)


on my system is 200(200) too, using gcc.
I think that being an undefined behavior according to the standard,
as Martin pointed out, the developers of the compiler used by user
have made up a mess. gcc handles it logically, as I have explained
(hope to be correct) in my earlier followup.

Now, user, which compiler have you used? I'm curious about it.

Bye
Daniele "tinybyte" Milan

Nov 14 '05 #11
user wrote:
Hello,
Please don't top-post. It's rude.

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?


Yes. This should be fairly obvious.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #12
tinybyte wrote:
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);


These last two statements invoke undefined behavior. %p is for void
pointers only. It's also a little silly to add your own 0x prefix. On
some implementations you'll get output like

0x0x034aff30
}

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 :)


There's no good reason to try to explain undefined behavior. In this
case, the compiler probably eliminated a fetch from memory by using the
value 100 directly, since it "knew" that's what the stored value would be.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #13
>When /can/ the address of a named object change?
sorry I wanted to say the adress that the pointer points to
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'm not sure about this but I think that when you write int *p=20; the
compiler will handle the memmory allocation of the int which has '20' value.
--

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

Remove (d*elete*) to reply


Nov 14 '05 #14
On Thu, 08 Jan 2004 10:39:30 +0000, Kevin Goodsell wrote:
There's no good reason to try to explain undefined behavior. In this
case, the compiler probably eliminated a fetch from memory by using the
value 100 directly, since it "knew" that's what the stored value would be.


There's always a good reason to try to know how things really works.
Now we had discovered that that compiler is broken. gcc handles the
thing correctly, as it should be. Just saying "according to the
standard" isn't enough. According to the standard that piece of code
is broken, but it actually executes, and sometimes properly.
You're not compiling programs with the standard, but with compilers.

Daniele
Nov 14 '05 #15
On Thu, 08 Jan 2004 10:39:30 +0000, Kevin Goodsell wrote:
These last two statements invoke undefined behavior. %p is for void
pointers only. It's also a little silly to add your own 0x prefix. On


I admit it's silly :)
Undefined behavior? then cast that pointers to void and you're done.

...
printf ("address of ip is %p\n", (void *)ip);
printf ("address of num is %p\n", (void *)&num);
...

Daniele
Nov 14 '05 #16
Frane Roje wrote:
I'm not sure about this but I think that when you write int *p=20; the
compiler will handle the memmory allocation of the int which has '20' value.


No, it will not. Unless You make p point somewhere decent first the
above is wrong.

--
Thomas

Nov 14 '05 #17
tinybyte <ne******@box.i t> wrote:
On Thu, 08 Jan 2004 14:57:21 +0530, Vijay Kumar R Zanvar wrote:
On my system the output is

value of num is 200(200)
on my system is 200(200) too, using gcc.
I think that being an undefined behavior according to the standard,
as Martin pointed out, the developers of the compiler used by user
have made up a mess.


No, the compiler used by the OP is quite as logical as gcc, and possibly
better at optimising - it seems to have diked out all references to the
const int and replaced them with the constant value, which is both a
sensible optimisation, and potentially quite a valuable one.
gcc handles it logically,


s/logically/lazily/, IYAM.

Richard
Nov 14 '05 #18
tinybyte <ne******@box.i t> wrote:
On Thu, 08 Jan 2004 10:39:30 +0000, Kevin Goodsell wrote:
There's no good reason to try to explain undefined behavior. In this
case, the compiler probably eliminated a fetch from memory by using the
value 100 directly, since it "knew" that's what the stored value would be.
There's always a good reason to try to know how things really works.
Now we had discovered that that compiler is broken. gcc handles the
thing correctly, as it should be.


Wrong, and wrong. The OP's compiler is quite correct, and gcc handles
this code as it _may_, not as it _should_ be handled. The code invokes
undefined behaviour - changing the value of a const object - and _any_
behaviour after that is correct.
Just saying "according to the
standard" isn't enough. According to the standard that piece of code
is broken, but it actually executes, and sometimes properly.
For _some_ values of properly. _My_ value of properly is the reverse -
I'd rather have a compiler that compiles correct code to a fast
executable than one that compiles incorrect code to appear to be
correct. Hence, I'd prefer the OP's compiler to gcc.
You're not compiling programs with the standard, but with compilers.


A meaningless statement, really.

Richard
Nov 14 '05 #19
tinybyte wrote:
On Thu, 08 Jan 2004 10:39:30 +0000, Kevin Goodsell wrote:
There's no good reason to try to explain undefined behavior. In this
case, the compiler probably eliminated a fetch from memory by using the
value 100 directly, since it "knew" that's what the stored value would be.

There's always a good reason to try to know how things really works.
Now we had discovered that that compiler is broken.


No we have not.
gcc handles the
thing correctly, as it should be.
No it does not. There is no right way and there is no wrong way.
Just saying "according to the
standard" isn't enough.
Yes it is.
According to the standard that piece of code
is broken, but it actually executes, and sometimes properly.
There is no properly.
You're not compiling programs with the standard, but with compilers.


Which conform to a standard. When the standard says that something is
undefined you cannot rely on the behaviour of any compiler when using
that something. The result will be different between different compilers
hence rendering your code unportable. The result will be different
between different versions of the same compiler. The result will even be
different for the same compiler invoked with different flags.

Try compiling with the optimising flags for gcc and be prepared to learn
a valuable lesson.

--
Thomas.

Nov 14 '05 #20

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

Similar topics

7
3695
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
6382
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
2182
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
1937
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
1747
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
1348
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
2239
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
1670
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
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9538
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
10470
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...
1
10214
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10023
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9067
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
7561
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
6803
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();...
2
3751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.