Hello guys,
while I'm studing some c codes i found this page:
http://www.nicksays.co.uk/2009/05/awesome-c-exam-question/
and this code:
#include <stdio.h>
int func (int a, int b) {
static int c = 1;
return a + b * (c *= -1);}
int main () {
int a = 2, b = 3;
int c = func(a, b);
a *= a++;
b *= ++b;
printf("%d %d %d %d\n", a, b, c, func(a, b));}
thats prints: 5 16 -1 21
then I made a similar php script:
<?php
function func ($a, $b) {
static $c =1;
return $a + $b * ($c *= -1);
}
function main() {
$a = 2;
$b = 3;
$c = func($a, $b);
$a *= $a++;
$b *= ++$b;
printf("%d %d %d %d\n", $a, $b, $c, func($a, $b));
}
main();
?>
and for my surprise its prints: 6 16 -1 22
so, somebody know and can explain me wtf happened?
Thanks!
Adir Kuhn
Hello guys,
while I'm studing some c codes i found this page:
http://www.nicksays.co.uk/2009/05/awesome-c-exam-question/and this code:
#include <stdio.h>
int func (int a, int b) {
static int c = 1;
return a + b * (c *= -1);}
int main () {
int a = 2, b = 3;
int c = func(a, b);a *= a++;
b *= ++b;
I'm no expert in C, but my understanding is that the two expressions immediately
above are UNDEFINED because there is only one sequence point, but the objects are
modified twice (*= and ++). See http://c-faq.com/expr/seqpoints.html
gcc appears to agree with me via the -Wsequence-point flag:
joey@banshee:0$cat > a.c
#include <stdio.h>
int func (int a, int b) {
static int c = 1;
return a + b * (c *= -1);
}
int main () {
int a = 2, b = 3;
int c = func(a, b);
a *= a++;
b *= ++b;
printf("%d %d %d %d\n", a, b, c, func(a, b));
}
joey@banshee:0$gcc -Wsequence-point a.c
a.c: In function ‘main’:
a.c:12:4: warning: operation on ‘a’ may be undefined
a.c:13:4: warning: operation on ‘b’ may be undefined
If my interpretation is correct, I'm not sure how much time we need to spend
around the question.