473,799 Members | 3,197 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
Richard Bos wrote:


s/logically/lazily/, IYAM.

^^^^
?
DYM "ITYM"?

:)

--
Thomas.

Nov 14 '05 #21
But if I use a char* p="test";
In that case the computer will allocate some space for the array,
right?

--

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

Remove (d*elete*) to reply
Nov 14 '05 #22
Frane Roje wrote:
But if I use a char* p="test";
In that case the computer will allocate some space for the array,
right?


Yes, but this is different. The compiler will find memory for the string
literal, then you make the pointer point to it. (Note that the string
cannot be changed).

Memory is also allocated for the string when you do:

puts("test");

It is in fact also not impossible for the string in the call to puts and
the string pointed to by p to be the same string. Remember that the
value you get from evaluating "test" is a pointer. Also in the above you
are assigning to the pointer, not to wherever the pointer is pointing.

In the case of

int *ip;
*ip = 42;

You are dereferencing ip and you get whatever it is pointing to. Bad
thing. Note that 42 evaluated to an int not an address.

--
Thomas.

Nov 14 '05 #23
Thomas Stegen <ts*****@cis.st rath.ac.uk> wrote:
Richard Bos wrote:
s/logically/lazily/, IYAM.

^^^^
DYM "ITYM"?


If You Ask Me.

Richard
Nov 14 '05 #24
"Frane Roje" <frane.roje(d*e lete*)@st.hinet .hr> wrote:
But if I use a char* p="test";
In that case the computer will allocate some space for the array,
right?


Wrong. It will put a (unwritable!) string constant somewhere in memory,
and then make p point to it. The string constant being unwritable is
significant - you've been writing through that pointer in this thread,
and you cannot reliably do so if p points to a string constant.

Richard
Nov 14 '05 #25
In article <bt************ *@news.t-online.com> Martin Dickopp <ex************ ****@zero-based.org> writes:
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?


Since the behavior is undefined, virtually anything can happen.


I think the compiler performs optimisation. That is, because num is
defined to be constant the compiler is allowed to assume that in the
printf num is still 100, so it does not access the value stored at
num at all.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #26
On Thu, 08 Jan 2004 12:17:51 +0000, Thomas Stegen wrote:
Now we had discovered that that compiler is broken.
No we have not.


You're right.
gcc handles the
thing correctly, as it should be.


No it does not. There is no right way and there is no wrong way.


You're right.
Just saying "according to the
standard" isn't enough.


Yes it is.


No, it's not. We should go deeper than the standard. I want to learn
more than what's written in the standard, and you're helping me.
If we stop discussing when someone says "According to the standard there
is no reason to speak about this" no one will learn further, even if
possible. Now, please tell me, if this is comp.lang.c "We speak about
everything that is C related" or if "We speak only
about what is written in the C standard". Both are ok for me, but for the
latter I'll know I had to search
somewhere else for the huge deal of information we would be missing.
According to the standard that piece of code
is broken, but it actually executes, and sometimes properly.


There is no properly.


You're right.
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.


You're right, but I would have never learned the lesson if I sticked to
the "According to the standard" dogma. We cannot rely on the behaviour of
any compiler, but we can surely speak about every and each different
behaviour, and maybe learn something more. C language is standard +
compilers, not only standard, that's what I meant.
Try compiling with the optimising flags for gcc and be prepared to learn
a valuable lesson.


I've learned NOW. Many thanks to all of you. I want to learn, but I cannot
if we stop when the standard comes in.

Daniele
Nov 14 '05 #27
In article <pa************ *************** *@box.it> tinybyte <ne******@box.i t> writes:
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.


In what way is that compiler broken and gcc not? A compiler is allowed,
when it sees a declaration like
const int num = 100;
to assume that when you use "num" later in the program, your intention
is that the value 100 should be used.
According to the standard that piece of code
is broken, but it actually executes, and sometimes properly.


What is proper execution with a piece of code to which the standard
assigns no meaning?
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #28
In article <3f************ ***@news.indivi dual.net> rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
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.


What gcc probably does do (and the warning message you get suggests it)
is discarding the word const from the declaration of num. Normally gcc
performs the above optimisation.
gcc handles it logically,


s/logically/lazily/, IYAM.


Not lazy...
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #29
On Thu, 08 Jan 2004 12:21:13 +0000, Dik T. Winter wrote:
In what way is that compiler broken and gcc not? A compiler is allowed,
when it sees a declaration like
const int num = 100;
to assume that when you use "num" later in the program, your intention
is that the value 100 should be used.
But it returns the same address. That's inconsistent. It should be not
permitted if not according to the standard, but it is. This means:
compilers implementations are broken, not strictly following the standard.
What is proper execution with a piece of code to which the standard
assigns no meaning?


There is no proper execution, now I know.

Bye
Daniele
Nov 14 '05 #30

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
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
10247
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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();...
1
4135
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
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.