-3

I'm using fgetc to read and validate a stream from text file, one character at a time, but for some reason it reorders the characters. The text file contains something like "abc"

void newFunction(int i, int j, int k);

int main()
{
    FILE *fp;
    /...opens text file.../
    newFunction(fgetc(fp), fgetc(fp), fgetc(fp));
}

void newFunction(int i, int j, int k)
{
    printf("%d %d %d", i, j, k,);
}

I'm expecting a b c but why does my code give c b a?

reiallenramos
  • 1,235
  • 2
  • 21
  • 29
  • 4
    It is not defined in which order the arguments are evaluated. – Some programmer dude Apr 23 '17 at 05:58
  • @Someprogrammerdude you mean precedence? I'll try enclosing in parentheses. – reiallenramos Apr 23 '17 at 06:01
  • 2
    *Operator* precedence has nothing to do with it. It's simply that the arguments can be evaluated in any order. You will not know which `fgetc` call will be called first. Please read e.g. [this evaluation order reference](http://en.cppreference.com/w/c/language/eval_order) for more information. – Some programmer dude Apr 23 '17 at 06:04
  • 1
    No, @Someprogrammerdude means that you can't predict which `fgetc()` will be evaluated first. Also, it's terrible practice to "*shorten*" the code like this, and it's too specific to a given input file, you should not write a program to work with a given input file, a "*file format*" is more appropriate and in that case I recommend an array, `char abc[3]` and `fread()` perhaps? – Iharob Al Asimi Apr 23 '17 at 06:05
  • 1
    Possible duplicate of [Why are these constructs (using ++) undefined behavior?](http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior) – too honest for this site Apr 23 '17 at 06:16
  • You should get numbers as output since you used `%d`. Always copy-paste the _exact_ code, Preferably a [mcve] – Spikatrix Apr 23 '17 at 06:48
  • @Olaf Isn't this code an example for _unspecified_ behavior and not _undefined_ behavior? And since the linked question is about UB with `++` mania, I don't think this is a dupe of that one. – Spikatrix Apr 23 '17 at 06:52
  • @Olaf there is no UB here – M.M Apr 23 '17 at 08:49

1 Answers1

0
void newFunction(int i, int j, int k);

int main()
{
    FILE *fp;
    /...opens text file.../
    int i = fgetc(fp);
    int j = fgetc(fp);
    int k = fgetc(fp);
    newFunction(i,j,k);
}

void newFunction(int i, int j, int k)
{
    printf("%d %d %d", i, j, k);
}

You can do above to avoid ambiguity in order evaluating parameters.

M.M
  • 138,810
  • 21
  • 208
  • 365
Austin
  • 1,709
  • 20
  • 40