Sanjay Rajpal
Sanjay Rajpal

Reputation: 498

Programming in C - Problem

Following is the C Code :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int a,b,d;
void Values1()
{
    a=a*2;
    b=b-5;
}

void Values2(register int c)
{
    d+=b-c;
    a=a+10;
    b*=3;
}
int a,b;

int main()
{
    int i=7;
    Values2(i);
    Values1();
    printf("a=%d, b=%d, d=%d\n",a,b,d);
    system("pause");
}

It Gives a Compilation Error related to redefinition of 'a' and 'b' in MS Visual C++ 2010. Please help me in figuring out why this error has occured.

Upvotes: 0

Views: 146

Answers (4)

paxdiablo
paxdiablo

Reputation: 882386

Why do you have these two lines?

int a,b,d;
int a,b;

You only need to define the variables once. I'd suggest getting rid of the second line.


Some other things you may want to consider in the interests of furthering your skills.

  • Global variables are usually consider a bad thing. There are better ways to do it which encapsulate information much better, and will reduce the likelihood of problems down the track.
  • Use meaningful variable names. They only slow down the compiler the tiniest bit and will not affect your running speed, but they make your code so much easier to maintain.
  • I like to space out expressions to make them more readable as well, like d += b - c; instead of d+=b-c;.
  • Don't bother with the register keyword, it's a suggestion to the compiler and most modern compilers are far better than developers at figuring out how best to optimise code.
  • There are two canonical prototypes for main and int main() isn't one of them - use int main (void) if you don't care about program arguments.
  • On pre-C99 compilers, you should return 0 from main (C99 will return 0 for you if you reach the closing brace of main).

Upvotes: 3

pmg
pmg

Reputation: 108988

Your compiler is badly configured. Your program is legal C.

The re-declarations of a and b fall into the category of "tentative definition". A properly configured C compiler, cannot stop compilation because of that.

Upvotes: 3

Tobias W&#228;rre
Tobias W&#228;rre

Reputation: 803

Right after the definition of Values2(), there is the line int a,b; which will conflict with int a,b,d; before Values1(), so you can safely remove the line int a,b;.

Besides, to get good results, you may want to set tha values of a, b and c in the start of the main function to get consistent results.

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 75659

You define a and b in the global scope here:

int a,b,d;

and here

int a,b;

You can not define variables twice.

Upvotes: 4

Related Questions