You are not logged in. Please login at www.codechef.com to post your questions!

×

constant qualifier

this function is giving value 10 after modification in main but when printed in fun(), it is giving modified value.. how is this happening??

#include<stdio.h>

#include<conio.h>

void fun(const int *s)
{
printf("In this function %d\n",*s);
}

int main()

{

const int a = 10;

int *p = (int*)&a;

printf("before modification a=%d\n",a);

*(int*)&a = 12;

printf("after modification a=%d\n",a);
fun(&a);
getch();

return 0;

}

asked 30 Aug '13, 01:48

berwalajay's gravatar image

0★berwalajay
162
accept rate: 0%

edited 30 Aug '13, 08:27

tijoforyou's gravatar image

2★tijoforyou
4.2k52364


This is not an answer, just observation.

It seems, that you somehow change value of p

#include<stdio.h>

void fun(const int *s)
{
    printf("In this function %d\n",*s);
}

int main()
{
    const int a = 10;
    int *p = (int*)&a; // const int* to int*
    printf("before modification a=%d\n",a);

    *(int*)&a = 12;

    printf("after modification a=%d\n",a);
    printf("after modification p=%d\n",*p);
    fun(&a);
    //getch();

    return 0;
}

C/C++ is magical...

My gcc version

gcc version 4.5.3 (GCC)

Here are IdeOne results:

link

answered 30 Aug '13, 16:39

betlista's gravatar image

3★betlista ♦♦
16.9k49115225
accept rate: 11%

edited 30 Aug '13, 16:43

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×2

question asked: 30 Aug '13, 01:48

question was seen: 425 times

last updated: 30 Aug '13, 16:43

Related questions