I have noticed in many of my programs that later code can affect the outcomes of earlier code. for example:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#define A 1
#define W 1
#define K 1
#define DT 0.01
#define DX 0.01
#define XMAX 1
#define TMAX 1
#define TENS 1
#define DENS 1
int main(int argc, char *argv[])
{
double u[10]={0};
double v[10]={0};
double a[10]={0};
double local_equil;
double deviation;
double force;
double t;
int i;
int valid_input;
char *out_file;
FILE *output;
if(argc!=2){
printf("not correct number of arguments\n");
exit(EXIT_FAILURE);
}
valid_input = sscanf(argv[1],"%s",out_file);
printf("valid_input = %d\n",valid_input);
if(valid_input){
printf("%s\n",out_file);
printf("%d hooray\n",valid_input);
output = fopen(out_file,"w");
}
if(!valid_input){
printf("input fail\n");
exit(EXIT_FAILURE);
}
for(t=0;t<100;t+=DT){
u[0]=1;
for(i=1;i<2;i++){
local_equil = (u[i-1]+u[i+1])/2;
deviation = local_equil - u[i];
force = TENS * deviation;
a[i] = force/(DENS*DX);
}
fprintf(output,"u[0] = %9f ",u[0]);
for(i=1;i<2;i++){
u[i] = u[i] + v[i]*DT + 0.5 * a[i] * (DT*DT);
v[i] = v[i] + (a[i] * DT);
fprintf(output,"u[%d] = %9f ",i,u[i]);
}
fprintf(output,"u[2] = 0\n");
}
return(0);
}
This code always says it has an invalid input, no matter what is put as the command line argument. However, if the entirety of the for loops are commented out, the input is read correctly.
How is this possible, seeing as all the tests for valid input occur before those loops?
I'm presuming that either i'm being very stupid or this is a by-product of optimisation. I use GCC on linux
p.s. apologies for the disjointed code, it's been altered so much to try and get things to work that it's lost all elegance.