1

whats wrong with my code? im trying to return a value from function ignition_status, its not returning. I cant see any problem in my code.

#include<stdio.h> #include<stdint.h> const char * ignition_status(); const char *ign_st; int main() { printf("%s", ignition_status(1)); return 0; } const char * ignition_status(int st) { if(st==1) { const char *ign_st="ON"; } else { const char *ign_st="OFF"; } return ign_st; } 

Thanks...

5
  • 1
    Shouldn't your #includes have a filename? Commented Oct 28, 2015 at 2:12
  • 2
    const char *ign_st inside the if/else blocks. That declares a new variable. Which only exists within the if/else blocks. What you are returning is then the global ign_st which has never been set. Remove those const char * or declare it as a local variable outside the if/else block. If you do the latter then best to use a different variable name so as not to confuse it with the global definition. Commented Oct 28, 2015 at 2:13
  • I'm quite sure your code isn't compiling, not only not returning what you expect. Is this correct? Commented Oct 28, 2015 at 2:14
  • Hi guys, thanks for the reply. im getting an warning that "unused variable ign_st", i think i've declared globally. Commented Oct 28, 2015 at 2:22
  • @user6161 What have you changed? If you have declared a local variable then, yes, the global variable is now unused. It's a warning not an error. So either add code to use the global variable or remove the global variable. Can't tell you which is right as don't know what further you want to do with your program. Commented Oct 28, 2015 at 2:25

2 Answers 2

3

The comments are pointing you to the right direction, here is a working sample:

#include <stdio.h> const char * ignition_status(int st) { const char *ign_st; if(st==1) { ign_st="ON"; } else { ign_st="OFF"; } return ign_st; } int main() { printf("%s", ignition_status(1)); return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

2

Just remove const char * in front of ign_st in if/else statement:

#include<stdio.h> #include<stdint.h> const char * ignition_status(); const char *ign_st; int main() { printf("%s", ignition_status(1)); return 0; } const char * ignition_status(int st) { if(st==1) { ign_st="ON"; } else { ign_st="OFF"; } return ign_st; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.