-
January 7th, 2012, 08:44 AM
#1
[RESOLVED] Quick question about functions
I apologize if its been asked before but my search didn't yield the answers I was looking for.
I have been looking at C++ and I am just starting. I am coming from a C# background but even in that it is more of a hobby than a job so I am still far from being efficient in it.
My question is: In C++ will functions/methods have to be created at the top of the file?
For example:
C++
Code:
#include "stdafx.h"
#include <iostream>
// Function to do simple calculation and return the result
int Calc(int num1, int num2)
{
using namespace std;
return num1 * num2 + num1;
}
int main()
{
using namespace std;
// Create and initialize variables
int firstNum = 0;
int secNum = 0;
// Ask user to input numbers and assign values
cout << "Please enter first number: ";
cin >> firstNum;
cout << "Please enter second number: ";
cin >> secNum;
// Calculate and display result on console
cout << "\n\nTotal: " << Calc(firstNum, secNum) << endl;
system("Pause");
return 0;
}
C#
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
// Create and initialize variables
int firstNum = 0;
int secNum = 0;
// Ask user to input numbers and assign values
Console.Write("Please enter first number: ");
Int32.TryParse(Console.ReadLine(), out firstNum);
Console.Write("Please enter second number: ");
Int32.TryParse(Console.ReadLine(), out secNum);
// Calculate and display result on console
Console.WriteLine("\nTotal: {0}", Calc(firstNum, secNum));
Console.Write("\nPress any key to continue...");
Console.ReadKey();
}
// Function to do simple calculation and return the result
static int Calc(int num1, int num2)
{
return num1 * num2 + num1;
}
}
}
In C# they can be created at the bottom of the project. While this is a small code block in larger applications it seems like it would make code harder to maintain by having everything added to the top.
I have not gotten far on the tutorials yet and it may just be their way of doing it. I tried adding the function to the bottom of the file and it said identifier not found so that is why I wanted to ask people with experience if this is the way it has to be done or if there is a way that functions can be added to the bottom and still be ran.
Thanks in advance.
-
January 7th, 2012, 09:54 AM
#2
Re: Quick question about functions
You don't need to place function implementations on top. You can place it everywhere in any module included in your project. The only thing you must provide is to let know the compiler the function signature before the compilation of module where the function is called will begin.
So, you could do it like:
Code:
#include "stdafx.h"
#include <iostream>
// Function declaration
int Calc(int num1, int num2);
int main()
{
...
}
// function implementation
int Calc(int num1, int num2)
{
using namespace std;
return num1 * num2 + num1;
}
Placing the function declaration on the top would just allow you to omit the line with function declaration.
Victor Nijegorodov
-
January 7th, 2012, 04:10 PM
#3
Re: Quick question about functions
Originally Posted by Ubiquitous
My question is: In C++ will functions/methods have to be created at the top of the file?
In C/C++ function needs to be declared prior to being called.
Originally Posted by VictorN
Placing the function declaration on the top would just allow you to omit the line with function declaration.
Which means, function definition is a declaration as well.
Originally Posted by Ubiquitous
In C# they can be created at the bottom of the project.
Wrong. In C# a class function may be placed anywhere in the class scope. In general, C++ classes act the same.
But there's a very important thing to remember: C++ is not C#. If you program in C++, you forget everything you learned from C#. And vice versa. Different cultures, you know.
Best regards,
Igor
-
January 7th, 2012, 07:25 PM
#4
Re: Quick question about functions
Originally Posted by VictorN
You don't need to place function implementations on top. You can place it everywhere in any module included in your project. The only thing you must provide is to let know the compiler the function signature before the compilation of module where the function is called will begin.
So, you could do it like:
Code:
#include "stdafx.h"
#include <iostream>
// Function declaration
int Calc(int num1, int num2);
int main()
{
...
}
// function implementation
int Calc(int num1, int num2)
{
using namespace std;
return num1 * num2 + num1;
}
Placing the function declaration on the top would just allow you to omit the line with function declaration.
Hmm I see that works and I like this method better. It would allow a sort of index on the top containing all functions found in the file.
What do experienced programmers usually do? Are both way correct ways or is one way wrong and the other the right one? I would like to stick to correct programing principles rather than learning the wrong way or my own way of doing things.
Yes you are correct sorry for not specifying about c# being a class function. Also I am aware they are two different cultures with differences but even they must have some common ground between them that would help in learning about the other.
Thank you both for your input it has been insightful
-
January 7th, 2012, 10:48 PM
#5
Re: Quick question about functions
Originally Posted by Igor Vartanov
In C/C++ function needs to be declared prior to being called.
Only in C++ must functions be declared (or defined) before calling them.
In 'C' you don't need to declare functions, which makes 'C' a much more dangerous language to use, as calling undeclared functions can lead to undefined behaviour at runtime.
Regards,
Paul McKenzie
-
January 7th, 2012, 10:58 PM
#6
Re: Quick question about functions
Originally Posted by Ubiquitous
What do experienced programmers usually do?
Experienced programmers usually build multi-module programs.
The "Calc" function would have been called in more than one module. Therefore the declaration of Calc() would be in a header file that you would include. The body of the Calc() function would be in one and only one module, but the declaration would be in a header file.
Just take a look at any of those header files you're including. What do you see in them? For example <math.h>, <stdio.h>, etc.? You see declarations of functions such as fopen(), fclose(), etc.
Are both way correct ways or is one way wrong and the other the right one? I would like to stick to correct programing principles rather than learning the wrong way or my own way of doing things.
If Calc() were just a routine that is used in only one module, then any of those methods would be correct.
Yes you are correct sorry for not specifying about c# being a class function. Also I am aware they are two different cultures with differences but even they must have some common ground between them that would help in learning about the other.
The only problem with this is that too many C# programmers (and you can say the same thing about Java programmers) start to use C# techniques in a C++ program. What winds up happening is the C++ program they've produced is a total mess, buggy, memory leaks galore, etc.
Or worse they are trying to turn C++ into C# or Java by introducing totally unnecessary functions, classes, etc. (I've seen programmers try to introduce the "god" object concept to C++, just because in the other language they use, everything is derived from a single object).
Regards,
Paul McKenzie
-
January 8th, 2012, 03:37 AM
#7
Re: Quick question about functions
Originally Posted by Paul McKenzie
In 'C' you don't need to declare functions,
Partially true. Simple demo:
Code:
#include <stdio.h>
// there's no foo declaration
int main()
{
foo(5);
}
#ifdef OOPS
void
#endif
foo(int val)
{
printf("%d\n", val);
}
If you neglect every single aspect of building reliable and safe software, indeed C pretends to be smart and friendly guy (read, dangerous, according to Paul ).
Code:
D:\Temp\28>cl 28.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
28.c
d:\temp\28\28.c(14) : warning C4716: 'foo' : must return a value
Microsoft (R) Incremental Linker Version 10.00.40219.01
Copyright (C) Microsoft Corporation. All rights reserved.
/out:28.exe
28.obj
But once you decide your code style to be more strict, C becomes less friendly but more accurate in diagnostics.
Code:
D:\Temp\28>cl 28.c /D"OOPS"
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
28.c
28.c(12) : error C2371: 'foo' : redefinition; different basic types
That C2371 actually says: hey, I've just implied that foo has to return int as you provided no declaration for it, but found it returning nothing. Please make your code somewhat more adequate.
With this we return back to what I said earlier: in C a function needs to be declared prior to being called. Or better, you need it to be declared first to avoid any implication.
Originally Posted by Paul McKenzie
which makes 'C' a much more dangerous language to use, as calling undeclared functions can lead to undefined behaviour at runtime.
Well, sorry, maybe some C flavors are really that horrible, I don't know. I dealt with only MS and Borland products, and those are not that bad like you describe.
Best regards,
Igor
-
January 8th, 2012, 07:53 AM
#8
Re: Quick question about functions
Well, sorry, maybe some C flavors are really that horrible, I don't know. I dealt with only MS and Borland products, and those are not that bad like you describe.
The issue of not providing the prototypes would be a concern when calling a library function. For example, in your code, remove the #include <stdio.h>, and call printf() in a crazy fashion:
Code:
printf(215, 34.0, 234);
The code should compile. I have no idea what will happen when you run it.
I've dealt with 'C' compilers from way back (even before MS got into the 'C' business), and stuff like the code above brought in the idea of prototypes to the language (the original K&R version of 'C' did not have prototypes)
Regards,
Paul McKenzie
Last edited by Paul McKenzie; January 9th, 2012 at 12:30 PM.
-
January 9th, 2012, 11:51 AM
#9
Re: Quick question about functions
Originally Posted by Ubiquitous
Hmm I see that works and I like this method better. It would allow a sort of index on the top containing all functions found in the file.
This "sort of index" is a good idea, but is usually placed in an associated header file rather than in the cpp file; that way, the functions can be called by other cpp files as well.
Of course, it isn't always necessary to make 100% of the functions in a cpp file visible to other cpp files. In that case, considering declaring the functions as static or inline, and don't include their declarations in the header.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|