Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined or unspecified behaviour?

I was reading this article and they use the following example to explain undefined behaviour:

// PROGRAM 1
#include <stdio.h>
int f1() { printf ("Geeks"); return 1;}
int f2() { printf ("forGeeks"); return 1;}
int main() 
{ 
  int p = f1() + f2();  
  return 0; 
}

However, it seems to be about the order in which subexpressions are evaluated, and according to C standard (Annex J.1), it is an unspecified behaviour and not an undefined behaviour:

Unspecified behavior: The order in which subexpressions are evaluated and the order in which side effects take place, except as specified for the function-call () , &&, || , ? : , and comma operators (6.5)

Since I am very new to reading official specifications, I'm wondering if I did misunderstand the example or the documentation. I know this may seem very pedantic but I'm interested into learning these advanced topics the right way.

like image 869
infotic Avatar asked Jul 21 '17 15:07

infotic


1 Answers

The link you have provided in the question is given wrong example of undefined behavior. Evaluation of f1 and f2 in f1() + f2() will be unspecified. Note that standard says about side effects along with the order of evaluation

The order in which subexpressions are evaluated and the order in which side effects take place [...]

Side effects (output to the stdout) in the evaluation of f1 and f2 are not related and they are not causing any undefined behavior.

This is no different than the example below

int a = 1;
int b = 1, c;

c = a + b;

Order of evaluation of a and b is unspecified in the expression a + b.

like image 51
haccks Avatar answered Oct 15 '22 01:10

haccks