Difference of two pointers of the same type is always one.
#include<stdio.h>
#include<string.h>
int main(){
int a = 5,b = 10,c;
int *p = &a,*q = &b;
c = p - q;
printf("%d" , c);
return 0;
}
Output is 1.
I dont get the reasoning behind it
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The behavior is undefined.
C99 6.5.6 paragraph 9 says:
Paragraph 7 in the same section says:
Section 4 paragraph 2 says:
3.4.3 defines the term “undefined behavior” as:
Given the declaration:
it’s likely that evaluating
&b - &awill yield a result that seems reasonable, such as1or-1. (Reasonable results are always a possible symptom of undefined behavior; it’s undefined, not required to crash.) But the compiler is under no obligation to placeaandbat any particular locations in memory relative to each other, and even if it does so, the subtraction is not guaranteed to be meaningful. An optimizing compiler is free to transform your program in ways that assume that its behavior is well defined, resulting in code that can behave in arbitrarily bad ways if that assumption is violated.By writing
&b - &a, you are in effect promising the compiler that that’s a meaningful operation. As Henry Spencer famously said, “If you lie to the compiler, it will get is revenge.”Note that it’s not just the result of the subtraction that’s undefined, it’s the behavior of the program that evaluates it.
Oh, did I mention that the behavior is undefined?