473,808 Members | 2,807 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 3079
On Thu, 08 Jan 2004 21:00:37 GMT
tinybyte <ne******@box.i t> wrote:

<snip>
As I said above, I don't want to write crap code with those tricks in
it. I stick to the standard when writing code, or at least I try to :)
I want to write the best code I can, and be aware of *why* that kind
of code results in undefined behavior.
The *only* reason code invokes undefined behaviour is because it does
something the standard says is undefined behaviour. It is nothing to do
with what compilers do when said undefined behaviour is invoked.
This is *understanding* . The
other way is just *believing*, and that could lead to mistakes too.


Knowing what any given set of compilers and options does with undefined
behaviour does not tell you anything about undefined behaviour. It does
not even tel you why the behaviour was originally specified as
undefined since those choices where made before any compiler you are
likely to use was written.

Do you have to see someone killed by having mains electricity connected
across their heart before you believe it is a bad idea? Do you have to
write off your computer before agreeing that connecting the power supply
to the motherboard incorrectly (something which *was* possible with AT
PSUs)?
--
Flash Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spam, it is real and I read it.
Nov 14 '05 #61
begin followup to tinybyte:
[...] I don't want that. I will keep programming in C for my
whole life, because I love it.


Mhh. Puts the thread into different perspective.
There are a few strategies to avoid this kind of debugging experience.

The good old days : #define SYMBOL LITERAL;
Only for limited range : enum { SYMBOL = LITERAL };
Use write-protection of OS : static const TYPE = LITERAL;
Performance be damned : TYPE SYMBOL(void) { return LITERAL; }

--
Für Google, Tux und GPL!
Nov 14 '05 #62
Alexander Bartolich <al************ *****@gmx.at> writes:
The good old days : #define SYMBOL LITERAL;
Only for limited range : enum { SYMBOL = LITERAL };
Use write-protection of OS : static const TYPE = LITERAL;
Performance be damned : TYPE SYMBOL(void) { return LITERAL; }


Better performance : inline TYPE SYMBOL(void) { return LITERAL; }
--
"The fact that there is a holy war doesn't mean that one of the sides
doesn't suck - usually both do..."
--Alexander Viro
Nov 14 '05 #63
In article <pa************ *************** *@box.it>,
tinybyte <ne******@box.i t> wrote:
On Thu, 08 Jan 2004 13:20:48 +0000, pete wrote:
I hope you understand that the compiler can't be wrong
when there is no proper execution.


Compilers simply must not permit such a thing, if it gives an
undefined behavior.


"Undefined behavior" means that anything can happen, and whatever
happens is your fault (the programmers fault), and not the fault of the
compiler. And whatever the compiler does is correct: When the behavior
is undefined, then _any_ behavior that the compiler produces is correct
behavior.
Nov 14 '05 #64
In article <pa************ *************** *@box.it>,
tinybyte <ne******@box.i t> wrote:
On Thu, 08 Jan 2004 14:31:51 +0000, Dik T. Winter wrote:
No that is not inconsistent. The address *must* remain the same.
The question is: "must the compiler look at that address to see what
is there?" The answer to that question is *no* if the variable is
declared to be const, because the compiler is allowed to assume that
the value is not changed.
The compiler is allowed to assume that the value it's not changed, but
sometimes it is changed, sometimes not, depends on optimization.
This is inconsistent behavior for me, and in C programming this should
not be ALLOWED. That is all I'm talking about.


True. The programmer who wrote that code deserves a kick in the ***.
I'm trying to say that compilers aren't perfect. And that all those
standards everyone here care so much about are not of any help in this case.
A value that cannot be changed has been changed, under certain conditions.
That means something is broken.
Yes, the code that some stupid programmer wrote is broken.
Is the same as you have an application that normally gives perfect output,
but by using it in a different way it was written for, you can screw up
the whole thing. You should not be allowed to use it that way.
If you can, there is a bug.


True, some people shouldn't be allowed to write C programs.
Nov 14 '05 #65

On Thu, 8 Jan 2004, Ben Pfaff wrote:

Alexander Bartolich <al************ *****@gmx.at> writes:
The good old days : #define SYMBOL LITERAL;
Only for limited range : enum { SYMBOL = LITERAL };
Use write-protection of OS : static const TYPE = LITERAL;
Performance be damned : TYPE SYMBOL(void) { return LITERAL; }


Better performance : inline TYPE SYMBOL(void) { return LITERAL; }


After that last guy gets kicked upstairs: #define SYMBOL LITERAL

;-)
-Arthur

Nov 14 '05 #66
Kevin Goodsell <us************ *********@never box.com> writes:
tinybyte wrote:

[...]
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


When I use "%p", I find it useful to add something to make it clear
that the value being displayed is a pointer (since the output
generated by "%p" often looks like a number). I usually just surround
it with square brackets. For example:

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

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 14 '05 #67
On Thu, 8 Jan 2004 15:02:12 +0530, "user" <no**@none.co m> wrote in
comp.lang.c:
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
The C standard requires that a compiler issue a diagnostic for
constraint violations, of which there are none in your code. The
standard does not define "error messages" or "warning messages",
either would suffice to meet the standard's requirements for a
diagnostic.
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, the code invokes undefined behavior. Attempting to change the
value of an object defined as const is undefined behavior. A compiler
is never required by the standard to issue any diagnostic for
undefined behavior.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #68
tinybyte <ne******@box.i t> wrote in message news:<pa******* *************** ******@box.it>. ..
On Thu, 08 Jan 2004 14:20:15 +0000, Alex wrote:
Are you trying to say that all possible undefined behaviour must be detected
at compile time, resulting in an error? If not, what are you trying to say?


Yes, they should be detected, and result in an error.


That would be the ideal. A major part of the thinking behind the
concept of 'undefined behaviour' in C is that many of these
situations are extremely hard to detect - in practice, more or
less impossible in some cases with compiler technology as it was
around the time that the Standard was first created. The complexity
that would have to be added to detect all possible cases of undefined
behaviour is huge. Some would say that a compiler which added all
this error detection would have a higher quality of implementation;
others consider that this effort is better spent on improving the
compilation of correct code, perhaps by improving optimization.

The essential thinking is that the compiler can assume that coding
errors that lead to undefined behaviour never occur - it doesn't
need to consider the possibility in any way. This sometimes ends up
with the program accidentally doing exactly what the coder wanted,
but often with it misbehaving in bizarre ways. It will often do
the "right" thing if optimization is disabled, and go "wrong" when
optimized. All but one of the many instances I've looked at of "a
bug in the optimizer" have turned out to be undefined behaviour in
the code being compiled.
Nov 14 '05 #69
tinybyte <ne******@box.i t> writes:
On Thu, 08 Jan 2004 14:20:15 +0000, Alex wrote:
Are you trying to say that all possible undefined behaviour must
be detected at compile time, resulting in an error? If not, what
are you trying to say?


Yes, they should be detected, and result in an error.


That's simply not possible.

The major reason that the concept of "undefined behavior" exists in
the C language is that many errors cannot be detected, and many other
errors cannot be detected portably or without considerable runtime
overhead.

Consider something as simple as this:

void foo(int *ptr)
{
*ptr = 42;
}

If ptr is a valid pointer-to-int, this is ok. If it's not (either
because it's a null pointer or because it's invalid for any of a
number of other reasons), it invokes undefined behavior. If the
implementation were required to explicitly detect this error, it would
have to have a way of determining whether a pointer is valid; there's
no good way to do that.

I think most languages have instances of this kind of thing. The
better-defined ones enumerate what they are. C is somewhat unusual in
the number of things that invoke undefined behavior (some other
languages either require more run-time checking or disallow some of
the dangerous things, like pointer arithmetic, that C allows), but
it's difficult, if not impossible, to eliminate them entirely without
severely limiting the power of the language.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 14 '05 #70

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
5077
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
6384
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
2184
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
1938
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
1748
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
2241
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
2125
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
1672
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
9721
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...
1
10374
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
10113
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
9195
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...
0
6880
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
5547
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
5685
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4331
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
3859
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.